id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
10,800 | def readlevelsfile(filename) assert os path exists(filename)'cannot find the level file% (filenamethe os path exists(function will return true if the file specified by the string passed to the function exists if it does not existos path exists(returns false mapfile open(filename' 'each level must end with blank line content mapfile readlines(['\ \ 'mapfile close(levels [will contain list of level objects levelnum maptextlines [contains the lines for single level' map mapobj [the map object made from the data in maptextlines the file object for the level file that is opened for reading is stored in mapfile all of the text from the level file is stored as list of strings in the content variablewith blank line added to the end (the reason that this is done is explained later after the level objects are createdthey will be stored in the levels list the levelnum variable will keep track of how many levels are found inside the level file the maptextlines list will be list of strings from the content list for single map (as opposed to how content stores the strings of all maps in the level filethe mapobj variable will be list for linenum in range(len(content))process each line that was in the level file line content[linenumrstrip('\ \ 'email questions to the authoral@inventwithpython com |
10,801 | the for loop on line will go through each line that was read from the level file one line at time the line number will be stored in linenum and the string of text for the line will be stored in line any newline characters at the end of the string will be stripped off if ';in lineignore the linesthey're comments in the level file line line[:line find(';')any text that exists after semicolon in the map file is treated like comment and is ignored this is just like the sign for python comments to make sure that our code does not accidentally think the comment is part of the mapthe line variable is modified so that it only consists of the text up to (but not includingthe semicolon character (remember that this is only changing the string in the content list it is not changing the level file on the hard drive if line !''this line is part of the map maptextlines append(linethere can be maps for multiple levels in the map file the maptextlines list will contain the lines of text from the map file for the current level being loaded as long as the current line is not blankthe line will be appended to the end of maptextlines elif line ='and len(maptextlines blank line indicates the end of level' map in the file convert the text in maptextlines into level object when there is blank line in the map filethat indicates that the map for the current level has ended and future lines of text will be for the later levels note howeverthat there must at least be one line in maptextlines so that multiple blank lines together are not counted as the start and stop to multiple levels find the longest row in the map maxwidth - for in range(len(maptextlines))if len(maptextlines[ ]maxwidthmaxwidth len(maptextlines[ ]all of the strings in maptextlines need to be the same length (so that they form rectangle)so they should be padded with extra blank spaces until they are all as long as the longest string the for loop goes through each of the strings in maptextlines and updates maxwidth |
10,802 | when it finds new longest string after this loop finishes executingthe maxwidth variable will be set to the length of the longest string in maptextlines add spaces to the ends of the shorter rows this ensures the map will be rectangular for in range(len(maptextlines))maptextlines[ +(maxwidth len(maptextlines[ ])the for loop on line goes through the strings in maptextlines againthis time to add enough space characters to pad each to be as long as maxwidth convert maptextlines to map object for in range(len(maptextlines[ ]))mapobj append([]for in range(len(maptextlines))for in range(maxwidth)mapobj[xappend(maptextlines[ ][ ]the maptextlines variable just stores list of strings (each string in the list represents rowand each character in the string represents character at different column this is why line has the and indexes reversedjust like the shapes data structure in the tetromino game but the map object will have to be list of list of single-character strings such that mapobj[ ][yrefers to the tile at the xy coordinates the for loop on line adds an empty list to mapobj for each column in maptextlines the nested for loops on line and will fill these lists with single-character strings to represent each tile on the map this creates the map object that star pusher uses loop through the spaces in the map and find the @and characters for the starting game state startx none the and for the player' starting position starty none goals [list of (xytuples for each goal stars [list of (xyfor each star' starting position for in range(maxwidth)for in range(len(mapobj[ ]))if mapobj[ ][yin ('@''+')'@is player'+is player goal startx starty if mapobj[ ][yin (''+''*')is goal'*is star goal goals append((xy)email questions to the authoral@inventwithpython com |
10,803 | if mapobj[ ][yin ('$''*')'$is star stars append((xy)after creating the map objectthe nested for loops on lines and will go through each space to find the xy coordinates three things the player' starting position this will be stored in the startx and starty variableswhich will then be stored in the game state object later on line the starting position of all the stars these will be stored in the stars listwhich is later stored in the game state object on line the position of all the goals these will be stored in the goals listwhich is later stored in the level object on line rememberthe game state object contains all the things that can change this is why the player' position is stored in it (because the player can move aroundand why the stars are stored in it (because the stars can be pushed around by the playerbut the goals are stored in the level objectsince they will never move around basic level design sanity checks assert startx !none and starty !none'level % (around line %sin % is missing "@or "+to mark the start point (levelnum+ linenumfilename assert len(goals 'level % (around line %sin % must have at least one goal (levelnum+ linenumfilename assert len(stars>len(goals)'level % (around line %sin % is impossible to solve it has % goals but only % stars (levelnum+ linenumfilenamelen(goals)len(stars)at this pointthe level has been read in and processed to be sure that this level will work properlya few assertions must pass if any of the conditions for these assertions are falsethen python will produce an error (using the string from the assert statementsaying what is wrong with the level file the first assertion on line checks to make sure that there is player starting point listed somewhere on the map the second assertion on line checks to make sure there is at least one goal (or moresomewhere on the map and the third assertion on line checks to make sure that there is at least one star for each goal (but having more stars than goals is allowed create level object and starting game state object gamestateobj {'player'(startxstarty)'stepcounter' |
10,804 | 'stars'starslevelobj {'width'maxwidth'height'len(mapobj)'mapobj'mapobj'goals'goals'startstate'gamestateobjlevels append(levelobjfinallythese objects are stored in the game state objectwhich itself is stored in the level object the level object is added to list of level objects on line it is this levels list that will be returned by the readlevelsfile(function when all of the maps have been processed reset the variables for reading the next map maptextlines [mapobj [gamestateobj {levelnum + return levels now that this level is done processingthe variables for maptextlinesmapobjand gamestateobj should be reset to blank values for the next level that will be read in from the level file the levelnum variable is also incremented by for the next level' level number recursive functions before you can learn how the floodfill(function worksyou need to learn about recursion recursion is simple concepta recursive function is just function that calls itselflike the one in the following program(don' type the letters at the beginning of each line thougha def passfortytwowhenyoucallthisfunction(param) print('start of function ' if param ! print('you did not pass when you called this function ' print('fine will do it myself ' passfortytwowhenyoucallthisfunction( this is the recursive call if param = print('thank you for passing when you called this function ' print('end of function ' passfortytwowhenyoucallthisfunction( (in your own programsdon' make functions have names as long as passfortytwowhenyoucallthisfunction( ' just being stupid and silly stupilly email questions to the authoral@inventwithpython com |
10,805 | when you run this programthe function gets defined when the def statement on line executes the next line of code that is executed is line kwhich calls passfortytwowhenyoucallthisfunction(and passes (gasp! as resultthe function calls itself on line and passes we call this call the recursive call this is what our program outputsstart of function you did not pass when you called this function fine will do it myself start of function thank you for passing when you called this function end of function end of function notice that the --start of function |and --end of function |text appears twice let' figure out what exactly happens and what order it happens in on line kthe function is called and is passed for the param parameter line prints out --start of function |the condition on line will be true (since ! so line and will print out their messages line will then make callrecursivelyto the function and passes for the param parameter so execution starts on line again and prints out --start of function |line ' condition this time is falseso it skips to line and finds that condition to be true this causes line to be called and displays --thank you |on the screen then the last line of the functionline iwill execute to print out --end of function |and the function returns to the line that called it but rememberthe line of code that called the function was line and in this original callparam was set to the code goes down to line and checks the conditionwhich is false (since = is falseso it skips the print(call on line insteadit runs the print(call on line which makes --end of function |display for second time since it has reached the end of the functionit returns to the line of code that called this function callwhich was line there are no more lines of code after line kso the program terminates note that local variables are not just local to the functionbut to specific call of the function stack overflows each time function is calledthe python interpreter remembers which line of code made the call that way when the function returns python knows where to resume the execution remembering this takes up tiny bit of memory this isn' normally big dealbut take look at this code |
10,806 | def funky()funky(funky(if you run this programyou'll get large amount of output which looks like thisfile " :\test py"line in funky funky(file " :\test py"line in funky funky(file " :\test py"line in funky funky(file " :\test py"line in funky funky(file " :\test py"line in funky funky(runtimeerrormaximum recursion depth exceeded the funky(function does nothing but call itself and then in that callthe function calls itself again then it calls itself againand againand again each time it calls itselfpython has to remember what line of code made that call so that when the function returns it can resume the execution there but the funky(function never returnsit just keeps making calls to itself this is just like the infinite loop bugwhere the program keeps going and never stops to prevent itself from running out of memorypython will cause an error after you are calls deep and crash the program this type of bug is called stack overflow this code also causes stack overfloweven though there are no recursive functionsdef spam()eggs(def eggs()spam(spam(when you run this programit causes an error that looks like thisfile " :\test py"line in spam eggs(email questions to the authoral@inventwithpython com |
10,807 | file " :\test py"line in eggs spam(file " :\test py"line in spam eggs(file " :\test py"line in eggs spam(file " :\test py"line in spam eggs(runtimeerrormaximum recursion depth exceeded preventing stack overflows with base case in order to prevent stack overflow bugsyou must have base case where the function stops make new recursive calls if there is no base case then the function calls will never stop and eventually stack overflow will occur here is an example of recursive function with base case the base case is when the param parameter equals def fizz(param)print(paramif param = return fizz(param fizz( when you run this programthe output will look like this this program does not have stack overflow error because once the param parameter is set to the if statement' condition will be true and the function will returnand then the rest of the calls will also return in turn though if your code never reaches the base casethen this will cause stack overflow if we changed the fizz( call to fizz( )then the program' output would look like thisfile " :\rectest py"line in fizz fizz(param file " :\rectest py"line in fizz fizz(param file " :\rectest py"line in fizz |
10,808 | fizz(param file " :\rectest py"line in fizz print(paramruntimeerrormaximum recursion depth exceeded recursive calls and base cases will be used to perform the flood fill algorithmwhich is described next the flood fill algorithm the flood fill algorithm is used in star pusher to change all of the floor tiles inside the walls of the level to use the --inside floor|tile image instead of the --outside floor|tile (which all the tiles on the map are by defaultthe original floodfill(call is on line it will convert any tiles represented with the string (which represents an outdoor floorto 'ostring (which represents an indoor floor def floodfill(mapobjxyoldcharacternewcharacter) """changes any values matching oldcharacter on the map object to newcharacter at the (xypositionand does the same for the positions to the leftrightdownand up of (xy)recursively "" in this gamethe flood fill algorithm creates the inside/outside floor distinction this is "recursivefunction for more info on the flood fill algorithmsee if mapobj[ ][ =oldcharacter mapobj[ ][ynewcharacter line and converts the tile at the xy coordinate passed to floodfill(to the newcharacter string if it originally was the same as the oldcharacter string if len(mapobj and mapobj[ + ][ =oldcharacterfloodfill(mapobjx+ yoldcharacternewcharactercall right if and mapobj[ - ][ =oldcharacterfloodfill(mapobjx- yoldcharacternewcharactercall left if len(mapobj[ ] and mapobj[ ][ + =oldcharacterfloodfill(mapobjxy+ oldcharacternewcharactercall down if and mapobj[ ][ - =oldcharacterfloodfill(mapobjxy- oldcharacternewcharactercall up these four if statements check if the tile to the rightleftdownand up of the xy coordinate are the same as oldcharacterand if soa recursive call is made to floodfill(with those coordinates email questions to the authoral@inventwithpython com |
10,809 | to better understand how the floodfill(function workshere is version that does not use recursive callsbut instead uses list of xy coordinates to keep track of which spaces on the map should be checked and possibly changed to newcharacter def floodfill(mapobjxyoldcharacternewcharacter)spacestocheck [if mapobj[ ][ =oldcharacterspacestocheck append((xy)while spacestocheck ![]xy spacestocheck pop(mapobj[ ][ynewcharacter if len(mapobj and mapobj[ + ][ =oldcharacterspacestocheck append(( + )check right if and mapobj[ - ][ =oldcharacterspacestocheck append(( - )check left if len(mapobj[ ] and mapobj[ ][ + =oldcharacterspacestocheck append((xy+ )check down if and mapobj[ ][ - =oldcharacterspacestocheck append((xy- )check up if you would like to read more detailed tutorial on recursion that uses cats and zombies for an examplego to drawing the map def drawmap(mapobjgamestateobjgoals) """draws the map to surface objectincluding the player and stars this function does not call pygame display update()nor does it draw the "leveland "stepstext in the corner "" mapsurf will be the single surface object that the tiles are drawn onso that it is easy to position the entire map on the displaysurf surface object firstthe width and height must be calculated mapsurfwidth len(mapobjtilewidth mapsurfheight (len(mapobj[ ] (tileheight tilefloorheighttileheight mapsurf pygame surface((mapsurfwidthmapsurfheight) mapsurf fill(bgcolorstart with blank color on the surface the drawmap(function will return surface object with the entire map (and the player and starsdrawn on it the width and height needed for this surface have to be calculated from mapobj (which is done on line and the surface object that everything will be drawn |
10,810 | on is created on line to begin withthe entire surface object is painted to the background color on line draw the tile sprites onto this surface for in range(len(mapobj)) for in range(len(mapobj[ ])) spacerect pygame rect(( tilewidthy (tileheight tilefloorheight)tilewidthtileheight)the set of nested for loops on line and will go through every possible xy coordinate on the map and draw the appropriate tile image at that location if mapobj[ ][yin tilemappingbasetile tilemapping[mapobj[ ][ ]elif mapobj[ ][yin outsidedecomappingbasetile tilemapping['first draw the base ground/wall tile mapsurf blit(basetilespacerectthe basetile variable is set to the surface object of the tile image to be drawn at the iteration' current xy coordinate if the single-character string is in the outsidedecomapping dictionarythen tilemapping['(the single-character string for the basic outdoor floor tilewill be used if mapobj[ ][yin outsidedecomappingdraw any tree/rock decorations that are on this tile mapsurf blit(outsidedecomapping[mapobj[ ][ ]]spacerectadditionallyif the tile was listed in the outsidedecomapping dictionarythe corresponding tree or rock image should be drawn on top of the tile that was just drawn at that xy coordinate elif (xyin gamestateobj['stars']if (xyin goalsa goal and star are on this spacedraw goal first mapsurf blit(imagesdict['covered goal']spacerectthen draw the star sprite mapsurf blit(imagesdict['star']spacerectif there is star located at this xy coordinate on the map (which can be found out by checking for (xyin the list at gamestateobj['stars'])then star should be drawn at this xy email questions to the authoral@inventwithpython com |
10,811 | coordinate (which is done on line before the star is drawnthe code should first check if there is also goal at this locationin which casethe --covered goal|tile should be drawn first elif (xyin goalsdraw goal without star on it mapsurf blit(imagesdict['uncovered goal']spacerectif there is goal at this xy coordinate on the mapthen the --uncovered goal|should be drawn on top of the tile the uncovered goal is drawn because if execution has reached the elif statement on line we know that the elif statement' condition on line was false and there is no star that is also at this xy coordinate 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]spacerectreturn mapsurf finallythe drawmap(function checks if the player is located at this xy coordinateand if sothe player' image is drawn over the tile line is outside of the nested for loops that began on line and so by the time the surface object is returnedthe entire map has been drawn on it checking if the level is finished def islevelfinished(levelobjgamestateobj) """returns true if all the goals have stars in them "" for goal in levelobj['goals'] if goal not in gamestateobj['stars'] found space with goal but no star on it return false return true the islevelfinished(function returns true if all the goals are covered stars some levels could have more stars than goalsso it' important to check that all the goals are covered by starsrather than checking if all the stars are over goals the for loop on line goes through the goals in levelobj['goals'(which is list of tuples of xy coordinates for each goaland checks if there is star in the gamestateobj['stars'list that has those same xy coordinates (the not in operators |
10,812 | work here because gamestateobj['stars'is list of those same tuples of xy coordinatesthe first time the code finds goal with no star at the same positionthe function returns false if it gets through all of the goals and finds star on each of themislevelfinished(returns true def terminate() pygame quit( sys exit(this terminate(function is the same as in all the previous programs if __name__ ='__main__' main(after all the functions have been definedthe main(function is called on line to begin the game summary in the squirrel eat squirrel gamethe game world was pretty simplejust an infinite green plain with grass images randomly scattered around it the star pusher game introduced something newhaving uniquely designed levels with tile graphics in order to store these levels in format that the computer can readthey are typed out into text file and code in the program reads those files and creates the data structures for the level reallyrather than just make simple game with single mapthe star pusher program is more of system for loading custom maps based on the level file just by modifying the level filewe can change where wallsstarsand goals appear in the game world the star pusher program can handle any configuration that the level file is set to (as long as it passes the assert statements that ensure the map makes senseyou won' even have to know how to program python to make your own levels text editor program that modifies the starpusherlevels txt file is all that anyone needs to have their own level editor for the star pusher game for additional programming practiceyou can download buggy versions of star pusher from email questions to the authoral@inventwithpython com |
10,813 | four extra games included in this is the source code for four extra games unfortunatelyonly the source code (including commentsis in this without any detailed explanation of the code by nowyou can play these games and figure out how the code works by looking at the source code and comments the games areflippy an --othello|clone where the player tries to flip the computer ai player' tiles ink spill --flood it|clone that makes use of the flood fill algorithm four in row --connect four|clone against the computer ai player gemgem --bejeweled|clone where the player swaps gems to try to get three identical gems in row if you have any questions about the source code in this bookfeel free to email the author at al@inventwithpython com buggy versions of these programs are also available if you want to practice fixing bugs |
10,814 | flippyan "othelloclone othelloalso known by the generic name reversihas an board with tiles that are black on one side and white on the other the starting board looks like figure - each player takes turn placing down new tile of their color any of the opponent' tiles that are between the new tile and the other tiles of that color is flipped the goal of the game is to have as many of the tiles with your color as possible for examplefigure - is what it looks like if the white player places new white tile on space the starting reversi board has two white tiles and two black tiles email questions to the authoral@inventwithpython com white places new tile |
10,815 | the black tile at is in between the new white tile and the existing white tile at that black tile is flipped over and becomes new white tilemaking the board look like figure - black makes similar move nextplacing black tile on which flips the white tile at this results in board that looks like figure - white' move will flip over one of black' tiles black places new tilewhich flips over one of white' tiles tiles in all directions are flipped as long as they are in between the player' new tile and existing tile in figure - the white player places tile at and flips black tiles in both directions (marked by the linesthe result is in figure - |
10,816 | white' second move at will flip two of black' tiles the board after white' second move as you can seeeach player can quickly grab majority of the tiles on the board in just one or two moves players must always make move that captures at least one tile the game ends when player either cannot make moveor the board is completely full the player with the most tiles of their color wins you can learn more about reversi from wikipediaa text version of this game that uses print(and input(instead of pygame is featured in of --invent your own computer games with python|you can read that for details about how the computer ai' algorithm was put together the computer ai for this game is pretty goodbecause it is easy for computer to simulate every possible move and take the one that flips over the most tiles it usually beats me whenever play it source code for flippy this source code can be downloaded from the image files that flippy uses can be downloaded from flippy (an othello or reversi cloneemail questions to the authoral@inventwithpython com |
10,817 | by al sweigart al@inventwithpython com released under "simplified bsdlicense based on the "reversi pycode that originally appeared in "invent your own computer games with python" import randomsyspygametimecopy from pygame locals import fps frames per second to update the screen windowwidth width of the program' windowin pixels windowheight height in pixels spacesize width height of each space on the boardin pixels boardwidth how many columns of spaces on the game board boardheight how many rows of spaces on the game board white_tile 'white_tilean arbitrary but unique value black_tile 'black_tilean arbitrary but unique value empty_space 'empty_spacean arbitrary but unique value hint_tile 'hint_tilean arbitrary but unique value animationspeed integer from to higher is faster animation amount of space on the left right side (xmarginor above and below (ymarginthe game boardin pixels xmargin int((windowwidth (boardwidth spacesize) ymargin int((windowheight (boardheight spacesize) white ( black green brightblue brown ( textbgcolor brightblue textbgcolor green gridlinecolor black textcolor white hintcolor brown def main() global mainclockdisplaysurffontbigfontbgimage pygame init( |
10,818 | mainclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) pygame display set_caption('flippy' font pygame font font('freesansbold ttf' bigfont pygame font font('freesansbold ttf' set up the background image boardimage pygame image load('flippyboard png' use smoothscale(to stretch the board image to fit the entire board boardimage pygame transform smoothscale(boardimage(boardwidth spacesizeboardheight spacesize) boardimagerect boardimage get_rect( boardimagerect topleft (xmarginymargin bgimage pygame image load('flippybackground png' use smoothscale(to stretch the background image to fit the entire window bgimage pygame transform smoothscale(bgimage(windowwidthwindowheight) bgimage blit(boardimageboardimagerect run the main game while true if rungame(=false break def rungame() plays single game of reversi each time this function is called reset the board and game mainboard getnewboard( resetboard(mainboard showhints false turn random choice(['computer''player'] draw the starting board and ask the player what color they want drawboard(mainboard playertilecomputertile enterplayertile( make the surface and rect objects for the "new gameand "hintsbuttons newgamesurf font render('new game'truetextcolortextbgcolor newgamerect newgamesurf get_rect( newgamerect topright (windowwidth hintssurf font render('hints'truetextcolortextbgcolor email questions to the authoral@inventwithpython com |
10,819 | hintsrect hintssurf get_rect( hintsrect topright (windowwidth while truemain game loop keep looping for player and computer' turns if turn ='player' player' turn if getvalidmoves(mainboardplayertile=[] if it' the player' turn but they can' movethen end the game break movexy none while movexy =none keep looping until the player clicks on valid space determine which board data structure to use for display if showhints boardtodraw getboardwithvalidmoves(mainboardplayertile else boardtodraw mainboard checkforquit( for event in pygame event get()event handling loop if event type =mousebuttonup handle mouse click events mousexmousey event pos if newgamerect collidepoint(mousexmousey) start new game return true elif hintsrect collidepoint(mousexmousey) toggle hints mode showhints not showhints movexy is set to two-item tuple xy coordinateor none value movexy getspaceclicked(mousexmousey if movexy !none and not isvalidmove(mainboardplayertilemovexy[ ]movexy[ ]) movexy none draw the game board drawboard(boardtodraw drawinfo(boardtodrawplayertilecomputertileturn draw the "new gameand "hintsbuttons displaysurf blit(newgamesurfnewgamerect |
10,820 | displaysurf blit(hintssurfhintsrectmainclock tick(fpspygame display update(make the move and end the turn makemove(mainboardplayertilemovexy[ ]movexy[ ]trueif getvalidmoves(mainboardcomputertile![]only set for the computer' turn if it can make move turn 'computerelsecomputer' turnif getvalidmoves(mainboardcomputertile=[]if it was set to be the computer' turn but they can' movethen end the game break draw the board drawboard(mainboarddrawinfo(mainboardplayertilecomputertileturndraw the "new gameand "hintsbuttons displaysurf blit(newgamesurfnewgamerectdisplaysurf blit(hintssurfhintsrectmake it look like the computer is thinking by pausing bit pauseuntil time time(random randint( while time time(pauseuntilpygame display update(make the move and end the turn xy getcomputermove(mainboardcomputertilemakemove(mainboardcomputertilexytrueif getvalidmoves(mainboardplayertile![]only set for the player' turn if they can make move turn 'playerdisplay the final score drawboard(mainboardscores getscoreofboard(mainboarddetermine the text of the message to display if scores[playertilescores[computertile]text 'you beat the computer by % pointscongratulations!(scores[playertilescores[computertile]email questions to the authoral@inventwithpython com |
10,821 | elif scores[playertilescores[computertile] text 'you lost the computer beat you by % points (scores[computertilescores[playertile] else text 'the game was tie! textsurf font render(texttruetextcolortextbgcolor textrect textsurf get_rect( textrect center (int(windowwidth )int(windowheight ) displaysurf blit(textsurftextrect display the "play again?text with yes and no buttons text surf bigfont render('play again?'truetextcolortextbgcolor text rect text surf get_rect( text rect center (int(windowwidth )int(windowheight make "yesbutton yessurf bigfont render('yes'truetextcolortextbgcolor yesrect yessurf get_rect( yesrect center (int(windowwidth int(windowheight make "nobutton nosurf bigfont render('no'truetextcolortextbgcolor norect nosurf get_rect( norect center (int(windowwidth int(windowheight while true process events until the user clicks on yes or no checkforquit( for event in pygame event get()event handling loop if event type =mousebuttonup mousexmousey event pos if yesrect collidepoint(mousexmousey) return true elif norect collidepoint(mousexmousey) return false displaysurf blit(textsurftextrect displaysurf blit(text surftext rect displaysurf blit(yessurfyesrect displaysurf blit(nosurfnorect pygame display update( mainclock tick(fps |
10,822 | def translateboardtopixelcoord(xy) return xmargin spacesize int(spacesize )ymargin spacesize int(spacesize def animatetilechange(tilestofliptilecoloradditionaltile) draw the additional tile that was just laid down (otherwise we' have to completely redraw the board the board info if tilecolor =white_tile additionaltilecolor white else additionaltilecolor black additionaltilexadditionaltiley translateboardtopixelcoord(additionaltile[ ]additionaltile[ ] pygame draw circle(displaysurfadditionaltilecolor(additionaltilexadditionaltiley)int(spacesize pygame display update( for rgbvalues in range( int(animationspeed )) if rgbvalues rgbvalues elif rgbvalues rgbvalues if tilecolor =white_tile color tuple([rgbvalues rgbvalues goes from to elif tilecolor =black_tile color tuple([ rgbvalues rgbvalues goes from to for xy in tilestoflip centerxcentery translateboardtopixelcoord(xy pygame draw circle(displaysurfcolor(centerxcentery)int(spacesize pygame display update( mainclock tick(fps checkforquit( def drawboard(board) draw background of board displaysurf blit(bgimagebgimage get_rect() draw grid lines of the board for in range(boardwidth )email questions to the authoral@inventwithpython com |
10,823 | draw the horizontal lines startx ( spacesizexmargin starty ymargin endx ( spacesizexmargin endy ymargin (boardheight spacesize pygame draw line(displaysurfgridlinecolor(startxstarty)(endxendy) for in range(boardheight ) draw the vertical lines startx xmargin starty ( spacesizeymargin endx xmargin (boardwidth spacesize endy ( spacesizeymargin pygame draw line(displaysurfgridlinecolor(startxstarty)(endxendy) draw the black white tiles or hint spots for in range(boardwidth) for in range(boardheight) centerxcentery translateboardtopixelcoord(xy if board[ ][ =white_tile or board[ ][ =black_tile if board[ ][ =white_tile tilecolor white else tilecolor black pygame draw circle(displaysurftilecolor(centerxcentery)int(spacesize if board[ ][ =hint_tile pygame draw rect(displaysurfhintcolor(centerx centery ) def getspaceclicked(mousexmousey) return tuple of two integers of the board space coordinates where the mouse was clicked (or returns none not in any space for in range(boardwidth) for in range(boardheight) if mousex spacesize xmargin and mousex ( spacesize xmargin and mousey spacesize ymargin and mousey ( spacesize ymargin return (xy return none def drawinfo(boardplayertilecomputertileturn) |
10,824 | draws scores and whose turn it is at the bottom of the screen scores getscoreofboard(board scoresurf font render("player score% computer score% % ' turn(str(scores[playertile])str(scores[computertile])turn title())truetextcolor scorerect scoresurf get_rect( scorerect bottomleft ( windowheight displaysurf blit(scoresurfscorerect def resetboard(board) blanks out the board it is passedand sets up starting tiles for in range(boardwidth) for in range(boardheight) board[ ][yempty_space add starting pieces to the center board[ ][ white_tile board[ ][ black_tile board[ ][ black_tile board[ ][ white_tile def getnewboard() creates brand newempty board data structure board [ for in range(boardwidth) board append([empty_spaceboardheight return board def isvalidmove(boardtilexstartystart) returns false if the player' move is invalid if it is valid movereturns list of spaces of the captured pieces if board[xstart][ystart!empty_space or not isonboard(xstartystart) return false board[xstart][ystarttile temporarily set the tile on the board if tile =white_tile othertile black_tile else othertile white_tile email questions to the authoral@inventwithpython com |
10,825 | tilestoflip [ check each of the eight directions for xdirectionydirection in [[ ][ ][ ][ - ][ ][- - ][- ][- ]] xy xstartystart +xdirection +ydirection if isonboard(xyand board[ ][ =othertile the piece belongs to the other player next to our piece +xdirection +ydirection if not isonboard(xy) continue while board[ ][ =othertile +xdirection +ydirection if not isonboard(xy) break break out of while loopcontinue in for loop if not isonboard(xy) continue if board[ ][ =tile there are pieces to flip over go in the reverse direction until we reach the original spacenoting all the tiles along the way while true -xdirection -ydirection if =xstart and =ystart break tilestoflip append([xy] board[xstart][ystartempty_space make space empty if len(tilestoflip= if no tiles flippedthis move is invalid return false return tilestoflip def isonboard(xy) returns true if the coordinates are located on the board return > and and boardheight def getboardwithvalidmoves(boardtile) returns new board with hint markings dupeboard copy deepcopy(board |
10,826 | for xy in getvalidmoves(dupeboardtile) dupeboard[ ][yhint_tile return dupeboard def getvalidmoves(boardtile) returns list of ( ,ytuples of all valid moves validmoves [ for in range(boardwidth) for in range(boardheight) if isvalidmove(boardtilexy!false validmoves append((xy) return validmoves def getscoreofboard(board) determine the score by counting the tiles xscore oscore for in range(boardwidth) for in range(boardheight) if board[ ][ =white_tile xscore + if board[ ][ =black_tile oscore + return {white_tile:xscoreblack_tile:oscore def enterplayertile() draws the text and handles the mouse click events for letting the player choose which color they want to be returns [white_tileblack_tileif the player chooses to be white [black_tilewhite_tileif black create the text textsurf font render('do you want to be white or black?'truetextcolortextbgcolor textrect textsurf get_rect( textrect center (int(windowwidth )int(windowheight ) xsurf bigfont render('white'truetextcolortextbgcolor xrect xsurf get_rect( xrect center (int(windowwidth int(windowheight osurf bigfont render('black'truetextcolortextbgcolor email questions to the authoral@inventwithpython com |
10,827 | orect osurf get_rect( orect center (int(windowwidth int(windowheight while true keep looping until the player has clicked on color checkforquit( for event in pygame event get()event handling loop if event type =mousebuttonup mousexmousey event pos if xrect collidepoint(mousexmousey) return [white_tileblack_tile elif orect collidepoint(mousexmousey) return [black_tilewhite_tile draw the screen displaysurf blit(textsurftextrect displaysurf blit(xsurfxrect displaysurf blit(osurforect pygame display update( mainclock tick(fps def makemove(boardtilexstartystartrealmove=false) place the tile on the board at xstartystartand flip tiles returns false if this is an invalid movetrue if it is valid tilestoflip isvalidmove(boardtilexstartystart if tilestoflip =false return false board[xstart][ystarttile if realmove animatetilechange(tilestofliptile(xstartystart) for xy in tilestoflip board[ ][ytile return true def isoncorner(xy) returns true if the position is in one of the four corners return ( = and = or ( =boardwidth and = or ( = and =boardheightor ( =boardwidth and =boardheight |
10,828 | def getcomputermove(boardcomputertile) given board and the computer' tiledetermine where to move and return that move as [xylist possiblemoves getvalidmoves(boardcomputertile randomize the order of the possible moves random shuffle(possiblemoves always go for corner if available for xy in possiblemoves if isoncorner(xy) return [xy go through all possible moves and remember the best scoring move bestscore - for xy in possiblemoves dupeboard copy deepcopy(board makemove(dupeboardcomputertilexy score getscoreofboard(dupeboard)[computertile if score bestscore bestmove [xy bestscore score return bestmove def checkforquit() for event in pygame event get((quitkeyup))event handling loop if event type =quit or (event type =keyup and event key =k_escape) pygame quit( sys exit( if __name__ ='__main__' main(email questions to the authoral@inventwithpython com |
10,829 | ink spilla "flood itclone the game --flood it|begins with board filled with colored tiles on each turn the player chooses new color to paint the top left tile and any tiles adjacent to it of that same color this game makes use of the flood fill algorithm (described in the star pusher the goal of the game is to turn the entire board into single color before running out of turns this game also has settings screen where the player can change the size of the board and the difficulty of the game if the player gets board of the colorsthere are few other color schemes they can switch to as well source code for ink spill this source code can be downloaded from the image files that flippy uses can be downloaded from ink spill ( flood it clone by al sweigart al@inventwithpython com released under "simplified bsdlicense import randomsyswebbrowsercopypygame from pygame locals import there are different box sizesnumber of boxesand life depending on the "board sizesetting selected smallboxsize size is in pixels mediumboxsize largeboxsize smallboardsize size is in boxes |
10,830 | mediumboardsize largeboardsize smallmaxlife number of turns mediummaxlife largemaxlife fps windowwidth windowheight boxsize mediumboxsize palettegapsize palettesize easy arbitrary but unique value medium arbitrary but unique value hard arbitrary but unique value difficulty medium game starts in "mediummode maxlife mediummaxlife boardwidth mediumboardsize boardheight mediumboardsize white ( darkgray black red ( green blue yellow ( orange ( purple ( the first color in each scheme is the background colorthe next six are the palette colors colorschemes ((( )redgreenblueyelloworangepurple) (( )( )( )( )( )( )( )) (( )( )( )( )( )( )( )) (( )( )( )( )( )( )( )) (( )( )( )( )( )( )( ))email questions to the authoral@inventwithpython com |
10,831 | (( )( )( )( )( )( )( )) for in range(len(colorschemes)) assert len(colorschemes[ ]= 'color scheme % does not have exactly colors ( bgcolor colorschemes[ ][ palettecolors colorschemes[ ][ : def main() global fpsclockdisplaysurflogoimagespotimagesettingsimagesettingsbuttonimageresetbuttonimage pygame init( fpsclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) load images logoimage pygame image load('inkspilllogo png' spotimage pygame image load('inkspillspot png' settingsimage pygame image load('inkspillsettings png' settingsbuttonimage pygame image load('inkspillsettingsbutton png' resetbuttonimage pygame image load('inkspillresetbutton png' pygame display set_caption('ink spill' mousex mousey mainboard generaterandomboard(boardwidthboardheightdifficulty life maxlife lastpaletteclicked none while truemain game loop paletteclicked none resetgame false draw the screen displaysurf fill(bgcolor drawlogoandbuttons( drawboard(mainboard drawlifemeter(life drawpalettes( checkforquit( for event in pygame event get()event handling loop if event type =mousebuttonup mousexmousey event pos |
10,832 | if pygame rect(windowwidth settingsbuttonimage get_width() windowheight settingsbuttonimage get_height() settingsbuttonimage get_width() settingsbuttonimage get_height()collidepoint(mousexmousey) resetgame showsettingsscreen(clicked on settings button elif pygame rect(windowwidth resetbuttonimage get_width() windowheight settingsbuttonimage get_height(resetbuttonimage get_height() resetbuttonimage get_width() resetbuttonimage get_height()collidepoint(mousexmousey) resetgame true clicked on reset button else check if palette button was clicked paletteclicked getcolorofpaletteat(mousexmousey if paletteclicked !none and paletteclicked !lastpaletteclicked palette button was clicked that is different from the last palette button clicked (this check prevents the player from accidentally clicking the same palette twice lastpaletteclicked paletteclicked floodanimation(mainboardpaletteclicked life - resetgame false if haswon(mainboard) for in range( )flash border times flashborderanimation(whitemainboard resetgame true pygame time wait( pause so the player can bask in victory elif life = life is zeroso player has lost drawlifemeter( pygame display update( pygame time wait( for in range( ) flashborderanimation(blackmainboard resetgame true email questions to the authoral@inventwithpython com |
10,833 | pygame time wait( pause so the player can suffer in their defeat if resetgame start new game mainboard generaterandomboard(boardwidthboardheightdifficulty life maxlife lastpaletteclicked none pygame display update( fpsclock tick(fps def checkforquit() terminates the program if there are any quit or escape key events for event in pygame event get(quit)get all the quit events pygame quit(terminate if any quit events are present sys exit( for event in pygame event get(keyup)get all the keyup events if event key =k_escape pygame quit(terminate if the keyup event was for the esc key sys exit( pygame event post(eventput the other keyup event objects back def haswon(board) if the entire board is the same colorplayer has won for in range(boardwidth) for in range(boardheight) if board[ ][ !board[ ][ ] return false found different colorplayer has not won return true def showsettingsscreen() global difficultyboxsizeboardwidthboardheightmaxlifepalettecolorsbgcolor the pixel coordinates in this function were obtained by loading the inkspillsettings png image into graphics editor and reading the pixel coordinates from there handy trick origdifficulty difficulty origboxsize boxsize |
10,834 | screenneedsredraw true while true if screenneedsredraw displaysurf fill(bgcolor displaysurf blit(settingsimage( , ) place the ink spot marker next to the selected difficulty if difficulty =easy displaysurf blit(spotimage( ) if difficulty =medium displaysurf blit(spotimage( ) if difficulty =hard displaysurf blit(spotimage( ) place the ink spot marker next to the selected size if boxsize =smallboxsize displaysurf blit(spotimage( ) if boxsize =mediumboxsize displaysurf blit(spotimage( ) if boxsize =largeboxsize displaysurf blit(spotimage( ) for in range(len(colorschemes)) drawcolorschemeboxes( pygame display update( screenneedsredraw false by defaultdon' redraw the screen for event in pygame event get()event handling loop if event type =quit pygame quit( sys exit( elif event type =keyup if event key =k_escape esc key on settings screen goes back to game return not (origdifficulty =difficulty and origboxsize =boxsize elif event type =mousebuttonup screenneedsredraw true screen should be redrawn mousexmousey event pos syntactic sugar check for clicks on the difficulty buttons if pygame rect( collidepoint(mousexmousey) difficulty easy email questions to the authoral@inventwithpython com |
10,835 | elif pygame rect( collidepoint(mousexmousey) difficulty medium elif pygame rect( collidepoint(mousexmousey) difficulty hard check for clicks on the size buttons elif pygame rect( collidepoint(mousexmousey) small board size setting boxsize smallboxsize boardwidth smallboardsize boardheight smallboardsize maxlife smallmaxlife elif pygame rect( , collidepoint(mousexmousey) medium board size setting boxsize mediumboxsize boardwidth mediumboardsize boardheight mediumboardsize maxlife mediummaxlife elif pygame rect( collidepoint(mousexmousey) large board size setting boxsize largeboxsize boardwidth largeboardsize boardheight largeboardsize maxlife largemaxlife elif pygame rect( collidepoint(mousexmousey) clicked on the "learn programmingad webbrowser open(' web browser elif pygame rect( collidepoint(mousexmousey) clicked on the "back to gamebutton return not (origdifficulty =difficulty and origboxsize =boxsize for in range(len(colorschemes)) clicked on color scheme button if pygame rect( mediumboxsize mediumboxsize collidepoint(mousexmousey) bgcolor colorschemes[ ][ palettecolors colorschemes[ ][ : |
10,836 | def drawcolorschemeboxes(xyschemenum) draws the color scheme boxes that appear on the "settingsscreen for boxy in range( ) for boxx in range( ) pygame draw rect(displaysurfcolorschemes[schemenum][ boxy boxx ]( mediumboxsize boxxy mediumboxsize boxymediumboxsizemediumboxsize) if palettecolors =colorschemes[schemenum][ :] put the ink spot next to the selected color scheme displaysurf blit(spotimage( ) def flashborderanimation(colorboardanimationspeed= ) origsurf displaysurf copy( flashsurf pygame surface(displaysurf get_size() flashsurf flashsurf convert_alpha( for startendstep in (( )( - )) the first iteration on the outer loop will set the inner loop to have transparency go from to the second iteration will have it go from to this is the "flash for transparency in range(startendanimationspeed step) displaysurf blit(origsurf( ) rgb color flashsurf fill((rgbtransparency) displaysurf blit(flashsurf( ) drawboard(boarddraw board on top of the transparency layer pygame display update( fpsclock tick(fps displaysurf blit(origsurf( )redraw the original surface def floodanimation(boardpaletteclickedanimationspeed= ) origboard copy deepcopy(board floodfill(boardboard[ ][ ]paletteclicked for transparency in range( animationspeed) the "newboard slowly become opaque over the original board drawboard(origboard drawboard(boardtransparency pygame display update( fpsclock tick(fps def generaterandomboard(widthheightdifficulty=medium)email questions to the authoral@inventwithpython com |
10,837 | creates board data structure with random colors for each box board [for in range(width)column [for in range(height)column append(random randint( len(palettecolors )board append(columnmake board easier by setting some boxes to same color as neighbor determine how many boxes to change if difficulty =easyif boxsize =smallboxsizeboxestochange elseboxestochange elif difficulty =mediumif boxsize =smallboxsizeboxestochange elseboxestochange elseboxestochange change neighbor' colorsfor in range(boxestochange)randomly choose box whose color to copy random randint( width- random randint( height- randomly choose neighbors to change direction random randint( if direction = change left and up neighbor board[ - ][ =board[ ][yboard[ ][ - =board[ ][yelif direction = change right and down neighbor board[ + ][ =board[ ][yboard[ ][ + =board[ ][yelif direction = change right and up neighbor board[ ][ - =board[ ][yboard[ + ][ =board[ ][yelsechange left and down neighbor board[ ][ + =board[ ][yboard[ - ][ =board[ ][yreturn board |
10,838 | def drawlogoandbuttons() draw the ink spill logo and settings and reset buttons displaysurf blit(logoimage(windowwidth logoimage get_width() ) displaysurf blit(settingsbuttonimage(windowwidth settingsbuttonimage get_width()windowheight settingsbuttonimage get_height()) displaysurf blit(resetbuttonimage(windowwidth resetbuttonimage get_width()windowheight settingsbuttonimage get_height(resetbuttonimage get_height()) def drawboard(boardtransparency= ) the colored squares are drawn to temporary surface which is then drawn to the displaysurf surface this is done so we can draw the squares with transparency on top of displaysurf as it currently is tempsurf pygame surface(displaysurf get_size() tempsurf tempsurf convert_alpha( tempsurf fill(( ) for in range(boardwidth) for in range(boardheight) lefttop lefttoppixelcoordofbox(xy rgb palettecolors[board[ ][ ] pygame draw rect(tempsurf(rgbtransparency)(lefttopboxsizeboxsize) lefttop lefttoppixelcoordofbox( pygame draw rect(tempsurfblack(left- top- boxsize boardwidth boxsize boardheight ) displaysurf blit(tempsurf( ) def drawpalettes() draws the six color palettes at the bottom of the screen numcolors len(palettecolors xmargin int((windowwidth ((palettesize numcolors(palettegapsize (numcolors ))) for in range(numcolors) left xmargin ( palettesize( palettegapsize top windowheight palettesize pygame draw rect(displaysurfpalettecolors[ ](lefttoppalettesizepalettesize) pygame draw rect(displaysurfbgcolor(left top palettesize palettesize ) email questions to the authoral@inventwithpython com |
10,839 | def drawlifemeter(currentlife) lifeboxsize int((windowheight maxlife draw background color of life meter pygame draw rect(displaysurfbgcolor( (maxlife lifeboxsize)) for in range(maxlife) if currentlife >(maxlife )draw solid red box pygame draw rect(displaysurfred( ( lifeboxsize) lifeboxsize) pygame draw rect(displaysurfwhite( ( lifeboxsize) lifeboxsize) draw white outline def getcolorofpaletteat(xy) returns the index of the color in palettecolors that the and parameters are over returns none if and are not over any palette numcolors len(palettecolors xmargin int((windowwidth ((palettesize numcolors(palettegapsize (numcolors ))) top windowheight palettesize for in range(numcolors) find out if the mouse click is inside any of the palettes left xmargin ( palettesize( palettegapsize pygame rect(lefttoppalettesizepalettesize if collidepoint(xy) return return none no palette exists at these xy coordinates def floodfill(boardoldcolornewcolorxy) this is the flood fill algorithm if oldcolor =newcolor or board[ ][ !oldcolor return board[ ][ynewcolor change the color of the current box make the recursive call for any neighboring boxes if floodfill(boardoldcolornewcolorx yon box to the left if boardwidth floodfill(boardoldcolornewcolorx yon box to the right |
10,840 | if floodfill(boardoldcolornewcolorxy on box to up if boardheight floodfill(boardoldcolornewcolorxy on box to down def lefttoppixelcoordofbox(boxxboxy) returns the and of the left-topmost pixel of the xth yth box xmargin int((windowwidth (boardwidth boxsize) ymargin int((windowheight (boardheight boxsize) return (boxx boxsize xmarginboxy boxsize ymargin if __name__ ='__main__' main(email questions to the authoral@inventwithpython com |
10,841 | four-in- -rowa "connect fourclone the game --connect four|has board where the players take turns dropping tokens from the top of the board the tokens will fall from the top of each column and come to rest on the bottom of the board or on top of the topmost token in that column player wins when four of their tokens line up in row either horizontallyverticallyor diagonally the ai for this game is pretty good it simulates every possible move it can makethen simulates every possible move the human player can make in response to each of those movesand then simulates every possible move it can make in response to thatand then simulates every possible move the human player could make in response to each of those movesafter all that thinkingthe computer determines which move is most likely to lead to it winning so the computer is kind of tough to beat usually lose to it since there are seven possible moves you can make on your turn (unless some columns are full)and seven possible moves the opponent could makeand seven moves in response to thatand seven moves in response to thatthat means that on each turn the computer is considering , possible moves you can make the computer consider the game even further by setting the difficulty constant to higher numberbut when set to value larger than the computer takes long time to calculate its turn you can also make the computer easier by setting difficulty to then the computer only considers each of its moves and the player' possible responses to those moves if you set the difficulty to then the computer loses all intelligence and simply makes random moves source code for four-in- -row this source code can be downloaded from |
10,842 | the image files that flippy uses can be downloaded from four-in- -row ( connect four clone by al sweigart al@inventwithpython com released under "simplified bsdlicense import randomcopysyspygame from pygame locals import boardwidth how many spaces wide the board is boardheight how many spaces tall the board is assert boardwidth > and boardheight > 'board must be at least difficulty how many moves to look ahead (> is usually too slow spacesize size of the tokens and individual board spaces in pixels fps frames per second to update the screen windowwidth width of the program' windowin pixels windowheight height in pixels xmargin int((windowwidth boardwidth spacesize ymargin int((windowheight boardheight spacesize brightblue ( white ( bgcolor brightblue textcolor white red 'red black 'black empty none human 'human computer 'computer def main() global fpsclockdisplaysurfredpilerectblackpilerectredtokenimg global blacktokenimgboardimgarrowimgarrowrecthumanwinnerimg global computerwinnerimgwinnerrecttiewinnerimg pygame init( fpsclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight)email questions to the authoral@inventwithpython com |
10,843 | pygame display set_caption('four in row' redpilerect pygame rect(int(spacesize )windowheight int( spacesize )spacesizespacesize blackpilerect pygame rect(windowwidth int( spacesize )windowheight int( spacesize )spacesizespacesize redtokenimg pygame image load(' row_red png' redtokenimg pygame transform smoothscale(redtokenimg(spacesizespacesize) blacktokenimg pygame image load(' row_black png' blacktokenimg pygame transform smoothscale(blacktokenimg(spacesizespacesize) boardimg pygame image load(' row_board png' boardimg pygame transform smoothscale(boardimg(spacesizespacesize) humanwinnerimg pygame image load(' row_humanwinner png' computerwinnerimg pygame image load(' row_computerwinner png' tiewinnerimg pygame image load(' row_tie png' winnerrect humanwinnerimg get_rect( winnerrect center (int(windowwidth )int(windowheight ) arrowimg pygame image load(' row_arrow png' arrowrect arrowimg get_rect( arrowrect left redpilerect right arrowrect centery redpilerect centery isfirstgame true while true rungame(isfirstgame isfirstgame false def rungame(isfirstgame) if isfirstgame let the computer go first on the first gameso the player can see how the tokens are dragged from the token piles turn computer showhelp true else randomly choose who goes first if random randint( = turn computer else turn human |
10,844 | showhelp false set up blank board data structure mainboard getnewboard( while truemain game loop if turn =human human player' turn gethumanmove(mainboardshowhelp if showhelp turn off help arrow after the first move showhelp false if iswinner(mainboardred) winnerimg humanwinnerimg break turn computer switch to other player' turn else computer player' turn column getcomputermove(mainboard animatecomputermoving(mainboardcolumn makemove(mainboardblackcolumn if iswinner(mainboardblack) winnerimg computerwinnerimg break turn human switch to other player' turn if isboardfull(mainboard) completely filled board means it' tie winnerimg tiewinnerimg break while true keep looping until player clicks the mouse or quits drawboard(mainboard displaysurf blit(winnerimgwinnerrect pygame display update( fpsclock tick( for event in pygame event get()event handling loop if event type =quit or (event type =keyup and event key =k_escape) pygame quit( sys exit( elif event type =mousebuttonup return email questions to the authoral@inventwithpython com |
10,845 | def makemove(boardplayercolumn) lowest getlowestemptyspace(boardcolumn if lowest !- board[column][lowestplayer def drawboard(boardextratoken=none) displaysurf fill(bgcolor draw tokens spacerect pygame rect( spacesizespacesize for in range(boardwidth) for in range(boardheight) spacerect topleft (xmargin ( spacesize)ymargin ( spacesize) if board[ ][ =red displaysurf blit(redtokenimgspacerect elif board[ ][ =black displaysurf blit(blacktokenimgspacerect draw the extra token if extratoken !none if extratoken['color'=red displaysurf blit(redtokenimg(extratoken[' ']extratoken[' ']spacesizespacesize) elif extratoken['color'=black displaysurf blit(blacktokenimg(extratoken[' ']extratoken[' ']spacesizespacesize) draw board over the tokens for in range(boardwidth) for in range(boardheight) spacerect topleft (xmargin ( spacesize)ymargin ( spacesize) displaysurf blit(boardimgspacerect draw the red and black tokens off to the side displaysurf blit(redtokenimgredpilerectred on the left displaysurf blit(blacktokenimgblackpilerectblack on the right def getnewboard() board [ for in range(boardwidth) board append([emptyboardheight return board |
10,846 | def gethumanmove(boardisfirstmove) draggingtoken false tokenxtokeny nonenone while true for event in pygame event get()event handling loop if event type =quit pygame quit( sys exit( elif event type =mousebuttondown and not draggingtoken and redpilerect collidepoint(event pos) start of dragging on red token pile draggingtoken true tokenxtokeny event pos elif event type =mousemotion and draggingtoken update the position of the red token being dragged tokenxtokeny event pos elif event type =mousebuttonup and draggingtoken let go of the token being dragged if tokeny xmargin and tokenx windowwidth xmargin let go at the top of the screen column int((tokenx xmarginspacesize if isvalidmove(boardcolumn) animatedroppingtoken(boardcolumnred board[column][getlowestemptyspace(boardcolumn)red drawboard(board pygame display update( return tokenxtokeny nonenone draggingtoken false if tokenx !none and tokeny !none drawboard(board{' ':tokenx int(spacesize )' ':tokeny int(spacesize )'color':red} else drawboard(board if isfirstmove show the help arrow for the player' first move displaysurf blit(arrowimgarrowrect pygame display update( fpsclock tick( email questions to the authoral@inventwithpython com |
10,847 | def animatedroppingtoken(boardcolumncolor) xmargin column spacesize ymargin spacesize dropspeed lowestemptyspace getlowestemptyspace(boardcolumn while true +int(dropspeed dropspeed + if int(( ymarginspacesize>lowestemptyspace return drawboard(board{' ': ' ': 'color':color} pygame display update( fpsclock tick( def animatecomputermoving(boardcolumn) blackpilerect left blackpilerect top speed moving the black tile up while (ymargin spacesize) -int(speed speed + drawboard(board{' ': ' ': 'color':black} pygame display update( fpsclock tick( moving the black tile over ymargin spacesize speed while (xmargin column spacesize) -int(speed speed + drawboard(board{' ': ' ': 'color':black} pygame display update( fpsclock tick( dropping the black tile animatedroppingtoken(boardcolumnblack def getcomputermove(board) potentialmoves getpotentialmoves(boardblackdifficulty get the best fitness from the potential moves bestmovefitness - |
10,848 | for in range(boardwidth) if potentialmoves[ibestmovefitness and isvalidmove(boardi) bestmovefitness potentialmoves[ find all potential moves that have this best fitness bestmoves [ for in range(len(potentialmoves)) if potentialmoves[ =bestmovefitness and isvalidmove(boardi) bestmoves append( return random choice(bestmoves def getpotentialmoves(boardtilelookahead) if lookahead = or isboardfull(board) return [ boardwidth if tile =red enemytile black else enemytile red figure out the best move to make potentialmoves [ boardwidth for firstmove in range(boardwidth) dupeboard copy deepcopy(board if not isvalidmove(dupeboardfirstmove) continue makemove(dupeboardtilefirstmove if iswinner(dupeboardtile) winning move automatically gets perfect fitness potentialmoves[firstmove break don' bother calculating other moves else do other player' counter moves and determine best one if isboardfull(dupeboard) potentialmoves[firstmove else for countermove in range(boardwidth) dupeboard copy deepcopy(dupeboard if not isvalidmove(dupeboard countermove) continue makemove(dupeboard enemytilecountermove if iswinner(dupeboard enemytile) losing move automatically gets the worst fitness potentialmoves[firstmove- break email questions to the authoral@inventwithpython com |
10,849 | else do the recursive call to getpotentialmoves( results getpotentialmoves(dupeboard tilelookahead potentialmoves[firstmove+(sum(resultsboardwidthboardwidth return potentialmoves def getlowestemptyspace(boardcolumn) return the row number of the lowest empty row in the given column for in range(boardheight- - - ) if board[column][ =empty return return - def isvalidmove(boardcolumn) returns true if there is an empty space in the given column otherwise returns false if column (boardwidthor board[column][ !empty return false return true def isboardfull(board) returns true if there are no empty spaces anywhere on the board for in range(boardwidth) for in range(boardheight) if board[ ][ =empty return false return true def iswinner(boardtile) check horizontal spaces for in range(boardwidth ) for in range(boardheight) if board[ ][ =tile and board[ + ][ =tile and board[ + ][ =tile and board[ + ][ =tile return true check vertical spaces for in range(boardwidth) for in range(boardheight ) if board[ ][ =tile and board[ ][ + =tile and board[ ][ + =tile and board[ ][ + =tile |
10,850 | return true check diagonal spaces for in range(boardwidth ) for in range( boardheight) if board[ ][ =tile and board[ + ][ - =tile and board[ + ][ - =tile and board[ + ][ - =tile return true check diagonal spaces for in range(boardwidth ) for in range(boardheight ) if board[ ][ =tile and board[ + ][ + =tile and board[ + ][ + =tile and board[ + ][ + =tile return true return false if __name__ ='__main__' main(email questions to the authoral@inventwithpython com |
10,851 | gemgema "bejeweledclone --bejeweled|is game where gems fall to fill up board the player can swap any two adjacent gems to try to match three gems in row (vertically or horizontallybut not diagonallythe matched gems then disappearmaking way for new gems to fall from the top matching more than three gemsor causing chain reaction of gem matches will result in more points the player' score slowly drops over timeso the player must constantly be making new matches the game ends when no possible match can be made on the board source code for gemgem this source code can be downloaded from the image files that flippy uses can be downloaded from gemgem ( bejeweled clone by al sweigart al@inventwithpython com released under "simplified bsdlicense "" this program has "gem data structures"which are basically dictionaries with the following keys 'xand 'ythe location of the gem on the board , is the top left there is also rowaboveboard row that 'ycan be set to to indicate that it is above the board 'directionone of the four constant variables updownleftright this is the direction the gem is moving 'imagenumthe integer index into gemimages to denote which image this gem uses "" |
10,852 | import randomtimepygamesyscopy from pygame locals import fps frames per second to update the screen windowwidth width of the program' windowin pixels windowheight height in pixels boardwidth how many columns in the board boardheight how many rows in the board gemimagesize width height of each space in pixels numgemimages is the number of gem types you will need png image files named gem pnggem pngetc up to gem( - png numgemimages assert numgemimages > game needs at least types of gems to work nummatchsounds is the number of different sounds to choose from when match is made the wav files are named match wavmatch wavetc nummatchsounds moverate to larger num means faster animations deductspeed reduces score by point every deductspeed seconds purple ( lightblue ( blue red ( black brown highlightcolor purple color of the selected gem' border bgcolor lightblue background color on the screen gridcolor blue color of the game board gameovercolor red color of the "game overtext gameoverbgcolor black background color of the "game overtext scorecolor brown color of the text for the player' score the amount of space to the sides of the board to the edge of the window is used several timesso calculate it once here and store in variables xmargin int((windowwidth gemimagesize boardwidth ymargin int((windowheight gemimagesize boardheight constants for direction values up 'up down 'down left 'leftemail questions to the authoral@inventwithpython com |
10,853 | right 'right empty_space - an arbitrarynonpositive value rowaboveboard 'row above boardan arbitrarynoninteger value def main() global fpsclockdisplaysurfgemimagesgamesoundsbasicfontboardrects initial set up pygame init( fpsclock pygame time clock( displaysurf pygame display set_mode((windowwidthwindowheight) pygame display set_caption('gemgem' basicfont pygame font font('freesansbold ttf' load the images gemimages [ for in range( numgemimages+ ) gemimage pygame image load('gem% pngi if gemimage get_size(!(gemimagesizegemimagesize) gemimage pygame transform smoothscale(gemimage(gemimagesizegemimagesize) gemimages append(gemimage load the sounds gamesounds { gamesounds['bad swap'pygame mixer sound('badswap wav' gamesounds['match'[ for in range(nummatchsounds) gamesounds['match'append(pygame mixer sound('match% wavi) create pygame rect objects for each board space to do board-coordinate-to-pixel-coordinate conversions boardrects [ for in range(boardwidth) boardrects append([] for in range(boardheight) pygame rect((xmargin ( gemimagesize) ymargin ( gemimagesize) gemimagesize gemimagesize) boardrects[xappend( while true rungame( |
10,854 | def rungame() plays through single game when the game is overthis function returns initialize the board gameboard getblankboard( score fillboardandanimate(gameboard[]scoredrop the initial gems initialize variables for the start of new game firstselectedgem none lastmousedownx none lastmousedowny none gameisover false lastscorededuction time time( clickcontinuetextsurf none while truemain game loop clickedspace none for event in pygame event get()event handling loop if event type =quit or (event type =keyup and event key =k_escape) pygame quit( sys exit( elif event type =keyup and event key =k_backspace return start new game elif event type =mousebuttonup if gameisover return after games endsclick to start new game if event pos =(lastmousedownxlastmousedowny) this event is mouse clicknot the end of mouse drag clickedspace checkforgemclick(event pos else this is the end of mouse drag firstselectedgem checkforgemclick((lastmousedownxlastmousedowny) clickedspace checkforgemclick(event pos if not firstselectedgem or not clickedspace if not part of valid dragdeselect both firstselectedgem none clickedspace none email questions to the authoral@inventwithpython com |
10,855 | elif event type =mousebuttondown this is the start of mouse click or mouse drag lastmousedownxlastmousedowny event pos if clickedspace and not firstselectedgem this was the first gem clicked on firstselectedgem clickedspace elif clickedspace and firstselectedgem two gems have been clicked on and selected swap the gems firstswappinggemsecondswappinggem getswappinggems(gameboardfirstselectedgemclickedspace if firstswappinggem =none and secondswappinggem =none if both are nonethen the gems were not adjacent firstselectedgem none deselect the first gem continue show the swap animation on the screen boardcopy getboardcopyminusgems(gameboard(firstswappinggemsecondswappinggem) animatemovinggems(boardcopy[firstswappinggemsecondswappinggem][]score swap the gems in the board data structure gameboard[firstswappinggem[' ']][firstswappinggem[' ']secondswappinggem['imagenum' gameboard[secondswappinggem[' ']][secondswappinggem[' ']firstswappinggem['imagenum' see if this is matching move matchedgems findmatchinggems(gameboard if matchedgems =[] was not matching moveswap the gems back gamesounds['bad swap'play( animatemovinggems(boardcopy[firstswappinggemsecondswappinggem][]score gameboard[firstswappinggem[' ']][firstswappinggem[' ']firstswappinggem['imagenum' gameboard[secondswappinggem[' ']][secondswappinggem[' ']secondswappinggem['imagenum' else this was matching move scoreadd while matchedgems ![] remove matched gemsthen pull down the board |
10,856 | points is list of dicts that tells fillboardandanimate( where on the screen to display text to show how many points the player got points is list because if the player gets multiple matchesthen multiple points text should appear points [ for gemset in matchedgems scoreadd +( (len(gemset for gem in gemset gameboard[gem[ ]][gem[ ]empty_space points append({'points'scoreadd ' 'gem[ gemimagesize xmargin ' 'gem[ gemimagesize ymargin} random choice(gamesounds['match']play( score +scoreadd drop the new gems fillboardandanimate(gameboardpointsscore check if there are any new matches matchedgems findmatchinggems(gameboard firstselectedgem none if not canmakemove(gameboard) gameisover true draw the board displaysurf fill(bgcolor drawboard(gameboard if firstselectedgem !none highlightspace(firstselectedgem[' ']firstselectedgem[' '] if gameisover if clickcontinuetextsurf =none only render the text once in future iterationsjust use the surface object already in clickcontinuetextsurf clickcontinuetextsurf basicfont render('final score% (click to continue)(score) gameovercolorgameoverbgcolor clickcontinuetextrect clickcontinuetextsurf get_rect( clickcontinuetextrect center int(windowwidth )int(windowheight displaysurf blit(clickcontinuetextsurfclickcontinuetextrect elif score and time time(lastscorededuction deductspeed score drops over time email questions to the authoral@inventwithpython com |
10,857 | score - lastscorededuction time time( drawscore(score pygame display update( fpsclock tick(fps def getswappinggems(boardfirstxysecondxy) if the gems at the (xycoordinates of the two gems are adjacent then their 'directionkeys are set to the appropriate direction value to be swapped with each other otherwise(nonenoneis returned firstgem {'imagenum'board[firstxy[' ']][firstxy[' ']] ' 'firstxy[' '] ' 'firstxy[' '] secondgem {'imagenum'board[secondxy[' ']][secondxy[' ']] ' 'secondxy[' '] ' 'secondxy[' '] highlightedgem none if firstgem[' '=secondgem[' ' and firstgem[' '=secondgem[' '] firstgem['direction'left secondgem['direction'right elif firstgem[' '=secondgem[' ' and firstgem[' '=secondgem[' '] firstgem['direction'right secondgem['direction'left elif firstgem[' '=secondgem[' ' and firstgem[' '=secondgem[' '] firstgem['direction'up secondgem['direction'down elif firstgem[' '=secondgem[' ' and firstgem[' '=secondgem[' '] firstgem['direction'down secondgem['direction'up else these gems are not adjacent and can' be swapped return nonenone return firstgemsecondgem def getblankboard() create and return blank board data structure board [ for in range(boardwidth) board append([empty_spaceboardheight |
10,858 | return board def canmakemove(board) return true if the board is in state where matching move can be made on it otherwise return false the patterns in oneoffpatterns represent gems that are configured in way where it only takes one move to make triplet oneoffpatterns ((( , )( , )( , )) (( , )( , )( , )) (( , )( , )( , )) (( , )( , )( , )) (( , )( , )( , )) (( , )( , )( , )) (( , )( , )( , )) (( , )( , )( , )) the and variables iterate over each space on the board if we use to represent the currently iterated space on the boardthen this pattern(( , )( , )( , ))refers to identical gems being set up like this + that isgem is offset from the by ( , )gem is offset by ( , )and gem is offset by ( , in this casegem can be swapped to the left to form vertical three-in- -row triplet there are eight possible ways for the gems to be one move away from forming triplehence oneoffpattern has patterns for in range(boardwidth) for in range(boardheight) for pat in oneoffpatterns check each possible pattern of "match in next moveto see if possible move can be made if (getgemat(boardx+pat[ ][ ] +pat[ ][ ]= getgemat(boardx+pat[ ][ ] +pat[ ][ ]= getgemat(boardx+pat[ ][ ] +pat[ ][ ]!noneor (getgemat(boardx+pat[ ][ ] +pat[ ][ ]= getgemat(boardx+pat[ ][ ] +pat[ ][ ]= getgemat(boardx+pat[ ][ ] +pat[ ][ ]!none)email questions to the authoral@inventwithpython com |
10,859 | return true return true the first time you find pattern return false def drawmovinggem(gemprogress) draw gem sliding in the direction that its 'directionkey indicates the progress parameter is number from (just startingto (slide complete movex movey progress * if gem['direction'=up movey -int(progress gemimagesize elif gem['direction'=down movey int(progress gemimagesize elif gem['direction'=right movex int(progress gemimagesize elif gem['direction'=left movex -int(progress gemimagesize basex gem[' ' basey gem[' ' if basey =rowaboveboard basey - pixelx xmargin (basex gemimagesize pixely ymargin (basey gemimagesize pygame rect(pixelx movexpixely moveygemimagesizegemimagesize displaysurf blit(gemimages[gem['imagenum']] def pulldownallgems(board) pulls down gems on the board to the bottom to fill in any gaps for in range(boardwidth) gemsincolumn [ for in range(boardheight) if board[ ][ !empty_space gemsincolumn append(board[ ][ ] board[ ([empty_space(boardheight len(gemsincolumn))gemsincolumn def getgemat(boardxy) |
10,860 | if boardwidth or >boardheight return none else return board[ ][ def getdropslots(board) creates "drop slotfor each column and fills the slot with number of gems that that column is lacking this function assumes that the gems have been gravity dropped already boardcopy copy deepcopy(board pulldownallgems(boardcopy dropslots [ for in range(boardwidth) dropslots append([] count the number of empty spaces in each column on the board for in range(boardwidth) for in range(boardheight- - - )start from bottomgoing up if boardcopy[ ][ =empty_space possiblegems list(range(len(gemimages)) for offsetxoffsety in (( - )( )( )(- )) narrow down the possible gems we should put in the blank space so we don' end up putting an two of the same gems next to each other when they drop neighborgem getgemat(boardcopyx offsetxy offsety if neighborgem !none and neighborgem in possiblegems possiblegems remove(neighborgem newgem random choice(possiblegems boardcopy[ ][ynewgem dropslots[xappend(newgem return dropslots def findmatchinggems(board) gemstoremove [ list of lists of gems in matching triplets that should be removed boardcopy copy deepcopy(board loop through each spacechecking for adjacent identical gems email questions to the authoral@inventwithpython com |
10,861 | for in range(boardwidth) for in range(boardheight) look for horizontal matches if getgemat(boardcopyxy=getgemat(boardcopyx =getgemat(boardcopyx yand getgemat(boardcopyxy!empty_space targetgem boardcopy[ ][ offset removeset [ while getgemat(boardcopyx offsety=targetgem keep checkingin case there' more than gems in row removeset append(( offsety) boardcopy[ offset][yempty_space offset + gemstoremove append(removeset look for vertical matches if getgemat(boardcopyxy=getgemat(boardcopyxy =getgemat(boardcopyxy and getgemat(boardcopyxy!empty_space targetgem boardcopy[ ][ offset removeset [ while getgemat(boardcopyxy offset=targetgem keep checking if there' more than gems in row removeset append((xy offset) boardcopy[ ][ offsetempty_space offset + gemstoremove append(removeset return gemstoremove def highlightspace(xy) pygame draw rect(displaysurfhighlightcolorboardrects[ ][ ] def getdroppinggems(board) find all the gems that have an empty space below them boardcopy copy deepcopy(board droppinggems [ for in range(boardwidth) for in range(boardheight - - ) if boardcopy[ ][ =empty_space and boardcopy[ ][ !empty_space this space drops if not empty but the space below it is |
10,862 | droppinggems append{'imagenum'boardcopy[ ][ ]' ' ' ' 'direction'down boardcopy[ ][yempty_space return droppinggems def animatemovinggems(boardgemspointstextscore) pointstext is dictionary with keys ' '' 'and 'points progress progress at represents beginning means finished while progress animation loop displaysurf fill(bgcolor drawboard(board for gem in gemsdraw each gem drawmovinggem(gemprogress drawscore(score for pointtext in pointstext pointssurf basicfont render(str(pointtext['points']) scorecolor pointsrect pointssurf get_rect( pointsrect center (pointtext[' ']pointtext[' '] displaysurf blit(pointssurfpointsrect pygame display update( fpsclock tick(fps progress +moverate progress the animation little bit more for the next frame def movegems(boardmovinggems) movinggems is list of dicts with keys xydirectionimagenum for gem in movinggems if gem[' '!rowaboveboard board[gem[' ']][gem[' ']empty_space movex movey if gem['direction'=left movex - elif gem['direction'=right movex elif gem['direction'=down movey elif gem['direction'=up movey - board[gem[' 'movex][gem[' 'moveygem['imagenum' else gem is located above the board (where new gems come fromemail questions to the authoral@inventwithpython com |
10,863 | board[gem[' ']][ gem['imagenum'move to top row def fillboardandanimate(boardpointsscore) dropslots getdropslots(board while dropslots ![[]boardwidth do the dropping animation as long as there are more gems to drop movinggems getdroppinggems(board for in range(len(dropslots)) if len(dropslots[ ]! cause the lowest gem in each slot to begin moving in the down direction movinggems append({'imagenum'dropslots[ ][ ]' ' ' 'rowaboveboard'direction'down} boardcopy getboardcopyminusgems(boardmovinggems animatemovinggems(boardcopymovinggemspointsscore movegems(boardmovinggems make the next row of gems from the drop slots the lowest by deleting the previous lowest gems for in range(len(dropslots)) if len(dropslots[ ]= continue board[ ][ dropslots[ ][ del dropslots[ ][ def checkforgemclick(pos) see if the mouse click was on the board for in range(boardwidth) for in range(boardheight) if boardrects[ ][ycollidepoint(pos[ ]pos[ ]) return {' ' ' ' return none click was not on the board def drawboard(board) for in range(boardwidth) for in range(boardheight) pygame draw rect(displaysurfgridcolorboardrects[ ][ ] gemtodraw board[ ][ if gemtodraw !empty_space displaysurf blit(gemimages[gemtodraw]boardrects[ ][ ] |
10,864 | def getboardcopyminusgems(boardgems) creates and returns copy of the passed board data structure with the gems in the "gemslist removed from it gems is list of dictswith keys xydirectionimagenum boardcopy copy deepcopy(board remove some of the gems from this board data structure copy for gem in gems if gem[' '!rowaboveboard boardcopy[gem[' ']][gem[' ']empty_space return boardcopy def drawscore(score) scoreimg basicfont render(str(score) scorecolor scorerect scoreimg get_rect( scorerect bottomleft ( windowheight displaysurf blit(scoreimgscorerect if __name__ ='__main__' main(summary hope these game programs have given you your own ideas about what games you' like to make and how you can write the code for them even if you don' have any ideas of your ownit' great practice to try to program clones of other games you've played here are several websites that can teach you more about programming pythongames that people have written that make use of the pygame library you can learn lot by downloading and reading other people' source code modules and functions pygame users that could help you with finding resources to learn programming email questions to the authoral@inventwithpython com |
10,865 | code for these programs and additional information this site also has the image and sound files used in the pygame programs games with python||which covers basic python programming you can look up if you need to learn about something specific the programs in this bookstep by step games al@inventwithpython com my email address feel free to email me your questions about this book or about python programming or you can find out more about python by searching the world wide web go to the search website web sites that can teach you more about python programming now get going and invent your own games and good luck |
10,866 | glossary alpha value the amount of transparency for color in pygamealpha values range from (completely transparentto (completely opaqueanti-aliasing technique for making shapes look smoother and less blocky by adding fuzzy colors to their edges anti-aliased drawings look smooth aliased drawings look blocky attributes variable that is part of an object for examplerect objects have members such as top and left which hold integer values for the rect object backwards compatibility writing code that is compatible with older versions of software python version has some backwards-incompatible features with python version but it is possible to write python programs that are backwards-compatible with python base case in recursionthe base case is the condition that stops further recursive function calls base case is necessary to prevent stack overflow errors blitting word that means copying the image on one surface object to another in programming in generalit means to copy one image to another image bounding rectangle the smallest rectangle that can be drawn around another shape camera view of particular part of the game world cameras are used when the game world is too large to fit on the player' screen caption in programmingthe caption is the text on the title bar of the window in pygamethe caption can be set with the pygame display set_caption(function cli seecommand line interface command line interface program that the user can use by seeing text on the screen and typing text through the keyboard old computers used to be able to only run cli programsbut new computers have graphical user interfaces constructor function the function that creates new object in pythonthese functions have the same name as the kind of objects they produce for examplepygame rect(creates rect objects display surface the surface object returned by the call to pygame display set_mode(this surface object is special because anything drawn on it email questions to the authoral@inventwithpython com |
10,867 | venture of iit bombay vjti alumni it provides very high-level dynamic data types and supports dynamic type checking it supports automatic garbage collection it can be easily integrated with cc++comactivexcorbaand java |
10,868 | venture of iit bombay vjti alumni python environment setup python is available on wide variety of platforms including linux and mac os let' understand how to set up our python environment local environment setup open terminal window and type "pythonto find out if it is already installed and which version is installed unix (solarislinuxfreebsdaixhp/uxsunosirixetc win /nt/ macintosh (intelppc kos/ dos (multiple versionspalmos nokia mobile phones windows ce acorn/risc os beos amiga |
10,869 | venture of iit bombay vjti alumni vms/openvms qnx vxworks psion python has also been ported to the java and net virtual machines installing python python distribution is available for wide variety of platforms you need to download only the binary code applicable for your platform and install python if the binary code for your platform is not availableyou need compiler to compile the source code manually compiling the source code offers more flexibility in terms of choice of features that you require in your installation here is quick overview of installing python on various platforms unix and linux installation here are the simple steps to install python on unix/linux machine open web browser and go to follow the link to download zipped source code available for unix/linux download and extract files editing the modules/setup file if you want to customize some options |
10,870 | venture of iit bombay vjti alumni run /configure script make make install this installs python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonxx where xx is the version of python windows installation here are the steps to install python on windows machine open web browser and go to follow the link for the windows installer python-xyz msi file where xyz is the version you need to install to use this installer python-xyz msithe windows system must support microsoft installer save the installer file to your local machine and then run it to find out if your machine supports msi run the downloaded file this brings up the python install wizardwhich is really easy to use just accept the default settingswait until the install is finishedand you are done |
10,871 | venture of iit bombay vjti alumni macintosh installation recent macs come with python installedbut it may be several years out of date see version along with extra tools to support development on the mac for older mac os' before mac os (released in )macpython is available jack jansen maintains it and you can have full access to the entire documentation at his website installation details for mac os installation setting up path programs and other executable files can be in many directoriesso operating systems provide search path that lists the directories that the os searches for executable the path is stored in an environment variablewhich is named string maintained by the operating system this variable contains information available to the command shell and other programs the path variable is named as path in unix or path in windows (unix is case sensitivewindows is notin mac osthe installer handles the path details to invoke the python interpreter from any particular directoryyou must add the python directory to your path |
10,872 | venture of iit bombay vjti alumni setting path at unix/linux to add the python directory to the path for particular session in unix in the csh shell type setenv path "$path:/usr/local/bin/pythonand press enter in the bash shell (linuxtype export ath="$path:/usr/local/bin/pythonand press enter in the sh or ksh shell type path="$path:/usr/local/bin/pythonand press enter note /usr/local/bin/python is the path of the python directory setting path at windows to add the python directory to the path for particular session in windows at the command prompt type path %path%; :\python and press enter note :\python is the path of the python directory python environment variables here are important environment variableswhich can be recognized by python sr no variable description |
10,873 | venture of iit bombay vjti alumni pythonpath it has role similar to path this variable tells the python interpreter where to locate the module files imported into program it should include the python source library directory and the directories containing python source code pythonpath is sometimes preset by the python installer pythonstartup it contains the path of an initialization file containing python source code it is executed every time you start the interpreter it is named as pythonrc py in unix and it contains commands that load utilities or modify pythonpath pythoncaseok it is used in windows to instruct python to find the first caseinsensitive match in an import statement set this variable to any value to activate it pythonhome |
10,874 | venture of iit bombay vjti alumni it is an alternative module search path it is usually embedded in the pythonstartup or pythonpath directories to make switching module libraries easy running python there are three different ways to start python interactive interpreter you can start python from unixdosor any other system that provides you command-line interpreter or shell window enter python the command line start coding right away in the interactive interpreter $python unix/linux or pythonunix/linux or :python windows/dos here is the list of all the available command line options |
10,875 | venture of iit bombay vjti alumni sr no option description - it provides debug output - it generates optimized bytecode (resulting in pyo files - do not run import site to look for python paths on startup - verbose output (detailed trace on import statements - disable class-based built-in exceptions (just use strings)obsolete starting with version |
10,876 | venture of iit bombay vjti alumni - cmd run python script sent in as cmd string file run python script from given file script from the command-line python script can be executed at command line by invoking the interpreter on your applicationas in the following $python script py unix/linux or pythonscript py unix/linux or >python script py windows/dos |
10,877 | venture of iit bombay vjti alumni note be sure the file permission mode allows execution integrated development environment you can run python from graphical user interface (guienvironment as wellif you have gui application on your system that supports python unix idle is the very first unix ide for python windows pythonwin is the first windows interface for python and is an ide with gui macintosh the macintosh version of python along with the idle ide is available from the main websitedownloadable as either macbinary or binhex' files if you are not able to set up the environment properlythen you can take help from your system admin make sure the python environment is properly set up and working perfectly fine note all the examples given in subsequent are executed with python version available on centos flavor of linux we already have set up python programming environment onlineso that you can execute all the available examples online at the same time when you are learning theory feel free to modify any example and execute it online |
10,878 | venture of iit bombay vjti alumni python basic syntax the python language has many similarities to perlcand java howeverthere are some definite differences between the languages first python program let us execute programs in different modes of programming interactive mode programming invoking the interpreter without passing script file as parameter brings up the following prompt python python (# nov : : [gcc (red hat - )on linux type "help""copyright""creditsor "licensefor more information |
10,879 | venture of iit bombay vjti alumni type the following text at the python prompt and press the enter print "hellopython!if you are running new version of pythonthen you would need to use print statement with parenthesis as in print ("hellopython!")however in python version this produces the following result hellopythonscript mode programming invoking the interpreter with script parameter begins execution of the script and continues until the script is finished when the script is finishedthe interpreter is no longer active let us write simple python program in script python files have extension py type the following source code in test py file print "hellopython! |
10,880 | venture of iit bombay vjti alumni we assume that you have python interpreter set in path variable nowtry to run this program as follows python test py this produces the following result hellopythonlet us try another way to execute python script here is the modified test py file #!/usr/bin/python print "hellopython!we assume that you have python interpreter available in /usr/bin directory nowtry to run this program as follows chmod + test py this is to make file executable /test py this produces the following result |
10,881 | venture of iit bombay vjti alumni hellopythonpython identifiers python identifier is name used to identify variablefunctionclassmodule or other object an identifier starts with letter to or to or an underscore (_followed by zero or more lettersunderscores and digits ( to python does not allow punctuation characters such as @$and within identifiers python is case sensitive programming language thusmanpower and manpower are two different identifiers in python here are naming conventions for python identifiers class names start with an uppercase letter all other identifiers start with lowercase letter starting an identifier with single leading underscore indicates that the identifier is private starting an identifier with two leading underscores indicates strongly private identifier if the identifier also ends with two trailing underscoresthe identifier is language-defined special name |
10,882 | venture of iit bombay vjti alumni reserved words the following list shows the python keywords these are reserved words and you cannot use them as constant or variable or any other identifier names all the python keywords contain lowercase letters only and exec not assert finally or break for pass class from print continue global raise def if return |
10,883 | venture of iit bombay vjti alumni del import try elif in while else is with except lambda yield lines and indentation python provides no braces to indicate blocks of code for class and function definitions or flow control blocks of code are denoted by line indentationwhich is rigidly enforced the number of spaces in the indentation is variablebut all statements within the block must be indented the same amount for example if trueprint "trueelse |
10,884 | venture of iit bombay vjti alumni print "falsehoweverthe following block generates an error if trueprint "answerprint "trueelseprint "answerprint "falsethusin python all the continuous lines indented with same number of spaces would form block the following example has various statement blocks note do not try to understand the logic at this point of time just make sure you understood various blocks even if they are without braces #!/usr/bin/python import sys |
10,885 | venture of iit bombay vjti alumni tryopen file stream file open(file_name" "except ioerrorprint "there was an error writing to"file_name sys exit(print "enter '"file_finishprint "when finishedwhile file_text !file_finishfile_text raw_input("enter text"if file_text =file_finishclose the file file close break |
10,886 | venture of iit bombay vjti alumni file write(file_textfile write("\ "file close(file_name raw_input("enter filename"if len(file_name= print "next time please enter somethingsys exit(tryfile open(file_name" "except ioerrorprint "there was an error reading filesys exit(file_text file read(file close( |
10,887 | venture of iit bombay vjti alumni print file_text multi-line statements statements in python typically end with new line python doeshoweverallow the use of the line continuation character (\to denote that the line should continue for example total item_one item_two item_three statements contained within the []{}or (brackets do not need to use the line continuation character for example days ['monday''tuesday''wednesday''thursday''friday'quotation in python python accepts single (')double ("and triple (''or """quotes to denote string literalsas long as the same type of quote starts and ends the string the triple quotes are used to span the string across multiple lines for exampleall the following are legal |
10,888 | venture of iit bombay vjti alumni word 'wordsentence "this is sentence paragraph """this is paragraph it is made up of multiple lines and sentences ""comments in python hash sign (#that is not inside string literal begins comment all characters after the and up to the end of the physical line are part of the comment and the python interpreter ignores them #!/usr/bin/python first comment print "hellopython!second comment this produces the following result hellopythonyou can type comment on the same line after statement or expression name "madisettithis is again comment |
10,889 | venture of iit bombay vjti alumni you can comment multiple lines as follows this is comment this is commenttoo this is commenttoo said that already using blank lines line containing only whitespacepossibly with commentis known as blank line and python totally ignores it in an interactive interpreter sessionyou must enter an empty physical line to terminate multiline statement waiting for the user the following line of the program displays the promptthe statement saying "press the enter key to exit"and waits for the user to take action #!/usr/bin/python raw_input("\ \npress the enter key to exit " |
10,890 | venture of iit bombay vjti alumni here"\ \nis used to create two new lines before displaying the actual line once the user presses the keythe program ends this is nice trick to keep console window open until the user is done with an application multiple statements on single line the semicolon allows multiple statements on the single line given that neither statement starts new code block here is sample snip using the semicolon import sysx 'foo'sys stdout write( '\ 'multiple statement groups as suites group of individual statementswhich make single code block are called suites in python compound or complex statementssuch as ifwhiledefand class require header line and suite header lines begin the statement (with the keywordand terminate with colon and are followed by one or more lines which make up the suite for example if expression suite elif expression |
10,891 | venture of iit bombay vjti alumni suite else suite command line arguments many programs can be run to provide you with some basic information about how they should be run python enables you to do this with - python - usagepython [option[- cmd - mod file -[argoptions and arguments (and corresponding environment variables)- cmd program passed in as string (terminates option list- debug output from parser (also pythondebug= - ignore environment variables (such as pythonpath- print this help message and exit etc |
10,892 | venture of iit bombay vjti alumni you can also program your script in such way that it should accept various options command line arguments is an advanced topic and should be studied bit later once you have gone through rest of the python concepts python variable types variables are nothing but reserved memory locations to store values this means that when you create variable you reserve some space in memory based on the data type of variablethe interpreter allocates memory and decides what can be stored in the reserved memory thereforeby assigning different data types to variablesyou can store integersdecimals or characters in these variables assigning values to variables python variables do not need explicit declaration to reserve memory space the declaration happens automatically when you assign value to variable the equal sign (=is used to assign values to variables the operand to the left of the operator is the name of the variable and the operand to the right of the operator is the value stored in the variable for example |
10,893 | venture of iit bombay vjti alumni #!/usr/bin/python counter an integer assignment miles floating point name "johna string print counter print miles print name here and "johnare the values assigned to countermilesand name variablesrespectively this produces the following result john multiple assignment python allows you to assign single value to several variables simultaneously for example |
10,894 | venture of iit bombay vjti alumni = = = herean integer object is created with the value and all three variables are assigned to the same memory location you can also assign multiple objects to multiple variables for example , , , ,"johnheretwo integer objects with values and are assigned to variables and respectivelyand one string object with the value "johnis assigned to the variable standard data types the data stored in memory can be of many types for examplea person' age is stored as numeric value and his or her address is stored as alphanumeric characters python has various standard data types that are used to define the operations possible on them and the storage method for each of them python has five standard data types numbers string list tuple |
10,895 | venture of iit bombay vjti alumni dictionary python numbers number data types store numeric values number objects are created when you assign value to them for example var var you can also delete the reference to number object by using the del statement the syntax of the del statement is del var [,var [,var ,varn]]]you can delete single object or multiple objects by using the del statement for example del var del var_avar_b python supports four different numerical types int (signed integerslong (long integersthey can also be represented in octal and hexadecimalfloat (floating point real values |
10,896 | venture of iit bombay vjti alumni complex (complex numbersexamples here are some examples of numbers int long float complex - - - - xdefabcecbdaecbfbael + - - + - - + |
10,897 | venture of iit bombay vjti alumni - - - python allows you to use lowercase with longbut it is recommended that you use only an uppercase to avoid confusion with the number python displays long integers with an uppercase complex number consists of an ordered pair of real floating-point numbers denoted by yjwhere and are the real numbers and is the imaginary unit python strings strings in python are identified as contiguous set of characters represented in the quotation marks python allows for either pairs of single or double quotes subsets of strings can be taken using the slice operator (and [:with indexes starting at in the beginning of the string and working their way from - at the end the plus (+sign is the string concatenation operator and the asterisk (*is the repetition operator for example #!/usr/bin/python str 'hello world! |
10,898 | venture of iit bombay vjti alumni print str prints complete string print str[ prints first character of the string print str[ : prints characters starting from rd to th print str[ :prints string starting from rd character print str prints string two times print str "testprints concatenated string this will produce the following result hello worldh llo llo worldhello world!hello worldhello world!test python lists lists are the most versatile of python' compound data types list contains items separated by commas and enclosed within square brackets ([]to some extent |
10,899 | venture of iit bombay vjti alumni lists are similar to arrays in one difference between them is that all the items belonging to list can be of different data type the values stored in list can be accessed using the slice operator (and [:]with indexes starting at in the beginning of the list and working their way to end - the plus (+sign is the list concatenation operatorand the asterisk (*is the repetition operator for example #!/usr/bin/python list 'abcd' 'john' tinylist [ 'john'print list prints complete list print list[ prints first element of the list print list[ : prints elements starting from nd till rd print list[ :prints elements starting from rd element print tinylist prints list two times print list tinylist prints concatenated lists |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.