id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
6,800 | break exit the loop when the user enters valid number print('please enter number greater than or quit 'print(handle the special cases if the user entered or if nth = print(' 'print(print('the # fibonacci number is 'continue elif nth = print(' 'print(print('the # fibonacci number is 'continue display warning if the user entered large numberif nth > print('warningthis will take while to display on the'print('screen if you want to quit this program before it is'print('donepress ctrl- 'input('press enter to begin 'calculate the nth fibonacci numbersecondtolastnumber lastnumber fibnumberscalculated print(' 'end=''display the first two fibonacci numbers display all the later numbers of the fibonacci sequencewhile truenextnumber secondtolastnumber lastnumber fibnumberscalculated + display the next number in the sequenceprint(nextnumberend=''check if we've found the nth number the user wantsif fibnumberscalculated =nthprint(print(print('the #'fibnumberscalculatedfibonacci ''number is 'nextnumbersep=''break print comma in between the sequence numbersprint(''end=''shift the last two numberssecondtolastnumber lastnumber lastnumber nextnumber fibonacci |
6,801 | experimental changes to it on your ownyou can also try to figure out how to do the followinguse different starting numbers than and create the next number by adding the previous three numbers instead of the previous two exploring the program this is base programso there aren' many options to customize it insteadconsiderhow could you use this programwhat other useful sequences could be programmed project # |
6,802 | ta watch your own virtual fish in virtual fish tankcomplete with air bubblers and kelp plants each time you run the programit randomly generates the fish using different fish types and colors take break and enjoy the calm serenity of this software aquariumor try programming in some virtual sharks to terrorize its inhabitantsyou can' run this program from your ide or editor this program uses the bext module and must be run from the command prompt or terminal in order to display correctly more information about the bext module can be found at |
6,803 | figure - show what the output will look like when you run fishtank py figure - the output of the fish tank programwith several fishkelp plantsand bubbles how it works modern graphical programs often generate animations by erasing their entire window and redrawing it or times second this gives them frame rate of or frames per second (fpsthe higher the fpsthe more fluid the animated movement appears drawing to terminal windows is much slower if we erased the entire terminal window to redraw its contents with the bext modulewe typically would only get about or fps this would cause noticeable flicker in the window we can speed this up by only drawing characters to the parts of the terminal window that have changed most of the fish tank program' output is empty spaceso to make the elements movethe clearaquarium(only has to draw space characters to the places where the fishkelpand bubbles currently are this increases our frame ratereduces flickeringand makes for much more pleasant fish tank animation """fish tankby al sweigart al@inventwithpython com peaceful animation of fish tank press ctrl- to stop similar to asciiquarium or @emojiaquariumbut mine is based on an older ascii fish tank program for dos project # |
6,804 | tagsextra-largeartisticbext"" import randomsystime try import bext except importerror print('this program requires the bext modulewhich you' print('can install by following the instructions at' print(' sys exit( set up the constants widthheight bext size( we can' print to the last column on windows without it adding newline automaticallyso reduce the width by one width - num_kelp (!try changing this to num_fish (!try changing this to or num_bubblers (!try changing this to or frames_per_second (!try changing this number to or (!try changing the constants to create fish tank with only kelp or only bubblers noteevery string in fish dictionary should be the same length fish_types {'right'['>']'left'['<']} {'right'['>||>']'left'['<||<']} {'right'['>))>']'left'['<[[<']} {'right'['>|| ''>|']'left'[' ||<'||<']} {'right'['>)) ''>)']'left'[' [[<'[[<']} {'right'['>-==>']'left'['<==-<']} {'right'[ '>\\>']'left'['<//<']} {'right'['>']'left'['<']} {'right'['}-[[[*>']'left'['<*]]]-{']} {'right'[']-']'left'['-[']} {'right'['>']'left'['<']} {'right'[' -^=>' ^=>' ' ^=>' ^=>'] 'left'['<=^ ''<= ' '<=^ -''<= ']} (!try adding your own fish to fish_types longest_fish_length longest single string in fish_types the and positions where fish runs into the edge of the screen left_edge right_edge width longest_fish_length top_edge bottom_edge height def main() global fishesbubblersbubbleskelpsstep fish tank |
6,805 | bext bg('black' bext clear( generate the global variables fishes [ for in range(num_fish) fishes append(generatefish() notebubbles are drawnbut not the bubblers themselves bubblers [ for in range(num_bubblers) each bubbler starts at random position bubblers append(random randint(left_edgeright_edge) bubbles [ kelps [ for in range(num_kelp) kelpx random randint(left_edgeright_edge kelp {' 'kelpx'segments'[] generate each segment of the kelp for in range(random randint( height )) kelp['segments'append(random choice(['('')']) kelps append(kelp run the simulation step while true simulateaquarium( drawaquarium( time sleep( frames_per_second clearaquarium( step + def getrandomcolor() """return string of random color "" return random choice(('black''red''green''yellow''blue' 'purple''cyan''white') def generatefish() """return dictionary that represents fish "" fishtype random choice(fish_types set up colors for each character in the fish text colorpattern random choice(('random''head-tail''single') fishlength len(fishtype['right'][ ] if colorpattern ='random'all parts are randomly colored colors [ for in range(fishlength) colors append(getrandomcolor() if colorpattern ='singleor colorpattern ='head-tail' colors [getrandomcolor()fishlength all the same color if colorpattern ='head-tail'head/tail different from body headtailcolor getrandomcolor( project # |
6,806 | colors[ headtailcolor set head color colors[- headtailcolor set tail color set up the rest of fish data structure fish {'right'fishtype['right'] 'left'fishtype['left'] 'colors'colors 'hspeed'random randint( ) 'vspeed'random randint( ) 'timetohdirchange'random randint( ) 'timetovdirchange'random randint( ) 'goingright'random choice([truefalse]) 'goingdown'random choice([truefalse]) 'xis always the leftmost side of the fish body fish[' 'random randint( width longest_fish_length fish[' 'random randint( height return fish def simulateaquarium() """simulate the movements in the aquarium for one step "" global fishesbubblersbubbleskelpstep simulate the fish for one step for fish in fishes move the fish horizontally if step fish['hspeed'= if fish['goingright'] if fish[' '!right_edge fish[' '+ move the fish right else fish['goingright'false turn the fish around fish['colors'reverse(turn the colors around else if fish[' '!left_edge fish[' '- move the fish left else fish['goingright'true turn the fish around fish['colors'reverse(turn the colors around fish can randomly change their horizontal direction fish['timetohdirchange'- if fish['timetohdirchange'= fish['timetohdirchange'random randint( turn the fish around fish['goingright'not fish['goingright' move the fish vertically if step fish['vspeed'= if fish['goingdown'] if fish[' '!bottom_edge fish[' '+ move the fish down else fish['goingdown'false turn the fish around fish tank |
6,807 | else if fish[' '!top_edge fish[' '- move the fish up else fish['goingdown'true turn the fish around fish can randomly change their vertical direction fish['timetovdirchange'- if fish['timetovdirchange'= fish['timetovdirchange'random randint( turn the fish around fish['goingdown'not fish['goingdown' generate bubbles from bubblers for bubbler in bubblers there is in chance of making bubble if random randint( = bubbles append({' 'bubbler' 'height } move the bubbles for bubble in bubbles diceroll random randint( if (diceroll = and (bubble[' '!left_edge) bubble[' '- bubble goes left elif (diceroll = and (bubble[' '!right_edge) bubble[' '+ bubble goes right bubble[' '- the bubble always goes up iterate over bubbles in reverse because ' deleting from bubbles while iterating over it for in range(len(bubbles - - ) if bubbles[ ][' '=top_edgedelete bubbles that reach the top del bubbles[ simulate the kelp waving for one step for kelp in kelps for ikelpsegment in enumerate(kelp['segments']) in chance to change waving if random randint( = if kelpsegment ='(' kelp['segments'][ ') elif kelpsegment =')' kelp['segments'][ '( def drawaquarium() """draw the aquarium on the screen "" global fishesbubblersbubbleskelpstep draw quit message bext fg('white' bext goto( print('fish tankby al sweigart ctrl- to quit 'end='' project # |
6,808 | draw the bubbles bext fg('white' for bubble in bubbles bext goto(bubble[' ']bubble[' '] print(random choice((' '' '))end='' draw the fish for fish in fishes bext goto(fish[' ']fish[' '] get the correct rightor left-facing fish text if fish['goingright'] fishtext fish['right'][step len(fish['right']) else fishtext fish['left'][step len(fish['left']) draw each character of the fish text in the right color for ifishpart in enumerate(fishtext) bext fg(fish['colors'][ ] print(fishpartend='' draw the kelp bext fg('green' for kelp in kelps for ikelpsegment in enumerate(kelp['segments']) if kelpsegment ='(' bext goto(kelp[' ']bottom_edge elif kelpsegment =')' bext goto(kelp[' ' bottom_edge print(kelpsegmentend='' draw the sand on the bottom bext fg('yellow' bext goto( height print(chr( (width )end=''draws sand sys stdout flush((required for bext-using programs def clearaquarium() """draw empty spaces over everything on the screen "" global fishesbubblersbubbleskelp draw the bubbles for bubble in bubbles bext goto(bubble[' ']bubble[' '] print('end='' draw the fish for fish in fishes bext goto(fish[' ']fish[' '] draw each character of the fish text in the right color print(len(fish['left'][ ])end='' fish tank |
6,809 | draw the kelp for kelp in kelps for ikelpsegment in enumerate(kelp['segments']) bext goto(kelp[' ']height print('end='' sys stdout flush((required for bext-using programs if this program was run (instead of imported)run the game if __name__ ='__main__' try main( except keyboardinterrupt sys exit(when ctrl- is pressedend the program after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingadd crabs that move along on the sandy bottom add an ascii-art castle that appears randomly on the sandy bottom make the fish randomly increase their speed for short burst exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change longest_fish_length on line to longest_fish_length what happens if you change 'right'fishtype['right'on line to 'right'fishtype['left'] what happens if you change bext fg('green'on line to bext fg('red') what happens if you delete or comment out clearaquarium(on line what happens if you change bext fg(fish['colors'][ ]on line to bext fg('random') what happens if you change random randint( on line to project # |
6,810 | flooder flooder is colorful game where player tries to fill the board with single color by changing the color of the tile in the upper-left corner this new color spreads to all neighboring tiles that matched the original color it' similar to the flood it mobile game this program also has colorblind modewhich uses shapes instead of flat colored tiles it relies on the recursive flood fill algorithm to paint the board and works similarly to the "paint bucketor "filltool in many painting applications |
6,811 | figure - shows what the output will look like when you run flooder py figure - the output of the flooder game in colorblind modeshowing distinct shapes instead of rectangles how it works accessibility is large issue in video gamesand addressing it can take many forms for exampledeuteranopiaor red-green colorblindnesscauses shades of red and green to appear the samemaking it hard to distinguish between red objects and green objects on the screen we can make flooder more accessible with mode that uses distinct shapes instead of distinct colors note that even the colorblind mode still uses color this means you can eliminate the "standardmodeif you wishand have even color-sighted users play in the colorblind mode the best accessibility designs are those that incorporate accessibility considerations from the start rather than add them as separate mode this reduces the amount of code we have to write and makes any future bug fixes easier other accessibility issues include making sure that text is large enough to be read without perfect visionthat sound effects have visual cues and spoken language has subtitles for those hard of hearingand that controls can be remapped to other keyboard keys so people can play the game with one hand the youtube channel game maker' toolkit has video series called "designing for disabilitythat covers many aspects of designing your games with accessibility in mind project # |
6,812 | colorful game where you try to fill the board with single color has mode for colorblind players inspired by the "flood it!game view this code at tagslargebextgame"" import randomsys try import bext except importerror print('this program requires the bext modulewhich you' print('can install by following the instructions at' print(' sys exit( set up the constants board_width (!try changing this to or board_height (!try changing this to or moves_per_game (!try changing this to or constants for the different shapes used in colorblind mode heart chr( character is ' diamond chr( character is ' spade chr( character is ' club chr( character is ' ball chr( character is '* triangle chr( character is '^ block chr( character is '# leftright chr( character is '- updown chr( character is '| downright chr( character is '+ downleft chr( character is '+ upright chr( character is '+ upleft chr( character is '+ list of chr(codes is at all the color/shape tiles used on the board tile_types ( colors_map { 'red' 'green' :'blue' :'yellow' :'cyan' :'purple' color_mode 'color mode shapes_map { heart triangle diamond ball club spade shape_mode 'shape mode def main() bext bg('black' bext fg('white'flooder |
6,813 | bext clear( print('''flooderby al sweigart al@inventwithpython com set the upper left color/shapewhich fills in all the adjacent squares of that color/shape try to make the entire board the same color/shape ''' print('do you want to play in colorblind modey/ ' response input('' if response upper(startswith(' ') displaymode shape_mode else displaymode color_mode gameboard getnewboard( movesleft moves_per_game while truemain game loop displayboard(gameboarddisplaymode print('moves left:'movesleft playermove askforplayermove(displaymode changetile(playermovegameboard movesleft - if haswon(gameboard) displayboard(gameboarddisplaymode print('you have won!' break elif movesleft = displayboard(gameboarddisplaymode print('you have run out of moves!' break def getnewboard() """return dictionary of new flood it board "" keys are (xytuplesvalues are the tile at that position board { create random colors for the board for in range(board_width) for in range(board_height) board[(xy)random choice(tile_types make several tiles the same as their neighbor this creates groups of the same color/shape for in range(board_width board_height) random randint( board_width random randint( board_height board[( )board[(xy) return board project # |
6,814 | """display the board on the screen "" bext fg('white' display the top edge of the board print(downright (leftright board_widthdownleft display each row for in range(board_height) bext fg('white' if = the first row begins with '> print('>'end='' elselater rows begin with white vertical line print(updownend='' display each tile in this row for in range(board_width) bext fg(colors_map[board[(xy)]] if displaymode =color_mode print(blockend='' elif displaymode =shape_mode print(shapes_map[board[(xy)]]end='' bext fg('white' print(updownrows end with white vertical line display the bottom edge of the board print(upright (leftright board_widthupleft def askforplayermove(displaymode) """let the player select color to paint the upper left tile "" while true bext fg('white' print('choose one of 'end='' if displaymode =color_mode bext fg('red' print('( )ed 'end='' bext fg('green' print('( )reen 'end='' bext fg('blue' print('( )lue 'end='' bext fg('yellow' print('( )ellow 'end='' bext fg('cyan' print('( )yan 'end='' bext fg('purple' print('( )urple 'end='' elif displaymode =shape_mode bext fg('red' print('( )eart'end='' bext fg('green' print('( )riangle'end='' bext fg('blue' print('( )iamond'end='' bext fg('yellow'flooder |
6,815 | print('( )all'end='' bext fg('cyan' print('( )lub'end='' bext fg('purple' print('( )pade'end='' bext fg('white' print('or quit:' response input(''upper( if response ='quit' print('thanks for playing!' sys exit( if displaymode =color_mode and response in tuple('rgbycp') return tile type number based on the response return {' ' ' ' ' ' ' ' ' ' ' ' }[response if displaymode =shape_mode and response in tuple('htdbcs') return tile type number based on the response return {' ' ' ' ' ': ' ' ' ' ' ' }[response def changetile(tiletypeboardxychartochange=none) """change the color/shape of tile using the recursive flood fill algorithm "" if = and = chartochange board[(xy) if tiletype =chartochange return base casealready is the same tile board[(xy)tiletype if and board[( )=chartochange recursive casechange the left neighbor' tile changetile(tiletypeboardx ychartochange if and board[(xy )=chartochange recursive casechange the top neighbor' tile changetile(tiletypeboardxy chartochange if board_width and board[( )=chartochange recursive casechange the right neighbor' tile changetile(tiletypeboardx ychartochange if board_height and board[(xy )=chartochange recursive casechange the bottom neighbor' tile changetile(tiletypeboardxy chartochange def haswon(board) """return true if the entire board is one color/shape "" tile board[( ) for in range(board_width) for in range(board_height) if board[(xy)!tile return false return true project # |
6,816 | if this program was run (instead of imported)run the game if __name__ ='__main__' main(after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingadd additional shapes and colors create other board shapes besides rectangle exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what error message do you get if you change board {on line to board [] what error message do you get if you change return board on line to return none what happens if you change movesleft - on line to movesleft - flooder |
6,817 | forest fire sim this simulation shows forest whose trees are constantly growing and then being burned down on each step of the simulationthere is percent chance that blank space grows into tree and percent chance that tree is struck by lightning and burns fires will spread to adjacent treesso densely packed forest is more likely to suffer larger fire than sparsely packed one this simulation was inspired by nicky case' emoji sim at |
6,818 | when you run forestfiresim pythe output will look like thisfigure - the forest fire simulationwith green as for trees and red ws for flames how it works this simulation is an example of emergent behavior--the interaction between simple parts in system creating complicated patterns empty spaces grow into treeslightning turns trees into fireand fire turns trees back into empty spaces while spreading to neighboring trees by adjusting the tree growth and lightning strike rateyou can cause the forest to display different phenomena for examplea low lightning chance but high growth rate causes largeconstant forest firessince the trees tend to be near each other and quickly replenish low growth rate but high lightning strike chance creates several small fires that quickly extinguish due to lack of nearby trees we don' explicitly program any of this behaviorratherit naturally emerges from the system that we created """forest fire simby al sweigart al@inventwithpython com simulation of wildfires spreading in forest press ctrl- to stop inspired by nicky case' emoji sim view this code at tagsshortbextsimulation"" import randomsystime try import bext forest fire sim |
6,819 | print('this program requires the bext modulewhich you' print('can install by following the instructions at' print(' sys exit( set up the constants width height tree ' fire ' empty (!try changing these settings to anything between and initial_tree_density amount of forest that starts with trees grow_chance chance blank space turns into tree fire_chance chance tree is hit by lightning burns (!try setting the pause length to or pause_length def main() forest createnewforest( bext clear( while truemain program loop displayforest(forest run single simulation step nextforest {'width'forest['width'] 'height'forest['height'] for in range(forest['width']) for in range(forest['height']) if (xyin nextforest if we've already set nextforest[(xy)on previous iterationjust do nothing here continue if ((forest[(xy)=empty and (random random(<grow_chance)) grow tree in this empty space nextforest[(xy)tree elif ((forest[(xy)=tree and (random random(<fire_chance)) lightning sets this tree on fire nextforest[(xy)fire elif forest[(xy)=fire this tree is currently burning loop through all the neighboring spaces for ix in range(- ) for iy in range(- ) project # |
6,820 | fire spreads to neighboring trees if forest get(( ixy iy)=tree nextforest[( ixy iy)fire the tree has burned down nowso erase it nextforest[(xy)empty else just copy the existing object nextforest[(xy)forest[(xy) forest nextforest time sleep(pause_length def createnewforest() """returns dictionary for new forest data structure "" forest {'width'width'height'height for in range(width) for in range(height) if (random random( <initial_tree_density forest[(xy)tree start as tree else forest[(xy)empty start as an empty space return forest def displayforest(forest) """display the forest data structure on the screen "" bext goto( for in range(forest['height']) for in range(forest['width']) if forest[(xy)=tree bext fg('green' print(treeend='' elif forest[(xy)=fire bext fg('red' print(fireend='' elif forest[(xy)=empty print(emptyend='' print( bext fg('reset'use the default font color print('grow chance{}format(grow_chance )end='' print('lightning chance{}format(fire_chance )end='' print('press ctrl- to quit ' if this program was run (instead of imported)run the game if __name__ ='__main__' try main( except keyboardinterrupt sys exit(when ctrl- is pressedend the program forest fire sim |
6,821 | experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingadd randomly created lakes and riverswhich act as fire breaks that flames cannot cross add percentage chance that tree will catch fire from its neighbor add different types of trees with different chances of catching fire add different states of burning trees so that it takes multiple simulation steps for tree to burn down exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change bext fg('green'on line to bext fg('random') what happens if you change empty on line to empty ' what happens if you change forest get(( ixy iy)=tree on line to forest get(( ixy iy)=empty what happens if you change nextforest[(xy)empty on line to nextforest[(xy)fire what happens if you change forest[(xy)empty on line to forest[(xy)tree project # |
6,822 | four in row in this classic tile-dropping board game for two playersyou must try to get four of your tiles in row horizontallyverticallyor diagonallywhile preventing your opponent from doing the same this program is similar to connect four |
6,823 | when you run fourinarow pythe output will look like thisfour in rowby al sweigart al@inventwithpython com --snip- ++player xenter column or quit + +player oenter column or quit --snip-player oenter column or quit +|xxx xo |ooooxo |oooxox |oxxxoxx+player has wonhow it works the board game projects in this book follow similar program structure there' often dictionary or list for representing the state of the boarda getnewboard(function that returns data structure for boarda display board(function for rendering board data structure on the screenand so on you can check out the other projects in this book with the board game tag and compare them with each otherespecially when you want to create your own original board game programs project # |
6,824 | tile-dropping game to get four in rowsimilar to connect four view this code at tagslargegameboard gametwo-player"" import sys constants used for displaying the board empty_space period is easier to count than space player_x ' player_o ' noteupdate displayboard(column_labels if board_width is changed board_width board_height column_labels (' '' '' '' '' '' '' ' assert len(column_labels=board_width def main() print("""four in rowby al sweigart al@inventwithpython com two players take turns dropping tiles into one of seven columnstrying to make four in row horizontallyverticallyor diagonally """ set up new game gameboard getnewboard( playerturn player_x while truerun player' turn display the board and get player' move displayboard(gameboard playermove askforplayermove(playerturngameboard gameboard[playermoveplayerturn check for win or tie if iswinner(playerturngameboard) displayboard(gameboarddisplay the board one last time print('player playerturn has won!' sys exit( elif isfull(gameboard) displayboard(gameboarddisplay the board one last time print('there is tie!' sys exit( switch turns to other player if playerturn =player_x playerturn player_o elif playerturn =player_o playerturn player_x def getnewboard()four in row |
6,825 | """returns dictionary that represents four in row board the keys are (columnindexrowindextuples of two integersand the values are one of the ' ''oor (empty spacestrings "" board { for columnindex in range(board_width) for rowindex in range(board_height) board[(columnindexrowindex)empty_space return board def displayboard(board) """display the board and its tiles on the screen "" '''prepare list to pass to the format(string method for the board template the list holds all of the board' tiles (and empty spacesgoing left to righttop to bottom:'' tilechars [ for rowindex in range(board_height) for columnindex in range(board_width) tilechars append(board[(columnindexrowindex)] display the board print("" + |{}{}{}{}{}{}{} |{}{}{}{}{}{}{} |{}{}{}{}{}{}{} |{}{}{}{}{}{}{} |{}{}{}{}{}{}{} |{}{}{}{}{}{}{} ++""format(*tilechars) def askforplayermove(playertileboard) """let player select column on the board to drop tile into returns tuple of the (columnrowthat the tile falls into "" while truekeep asking player until they enter valid move print('player {}enter column or quit:format(playertile) response input(''upper(strip( if response ='quit' print('thanks for playing!' sys exit( if response not in column_labels print('enter number from to {format(board_width) continue ask player again for their move columnindex int(response - for -based the index if the column is fullask for move again if board[(columnindex )!empty_space project # |
6,826 | print('that column is fullselect another one ' continue ask player again for their move starting from the bottomfind the first empty space for rowindex in range(board_height - - ) if board[(columnindexrowindex)=empty_space return (columnindexrowindex def isfull(board) """returns true if the `boardhas no empty spacesotherwise returns false "" for rowindex in range(board_height) for columnindex in range(board_width) if board[(columnindexrowindex)=empty_space return false found an empty spaceso return false return true all spaces are full def iswinner(playertileboard) """returns true if `playertilehas four tiles in row on `board` otherwise returns false "" go through the entire boardchecking for four-in- -row for columnindex in range(board_width ) for rowindex in range(board_height) check for horizontal four-in- -row going right tile board[(columnindexrowindex) tile board[(columnindex rowindex) tile board[(columnindex rowindex) tile board[(columnindex rowindex) if tile =tile =tile =tile =playertile return true for columnindex in range(board_width) for rowindex in range(board_height ) check for vertical four-in- -row going down tile board[(columnindexrowindex) tile board[(columnindexrowindex ) tile board[(columnindexrowindex ) tile board[(columnindexrowindex ) if tile =tile =tile =tile =playertile return true for columnindex in range(board_width ) for rowindex in range(board_height ) check for four-in- -row going right-down diagonal tile board[(columnindexrowindex) tile board[(columnindex rowindex ) tile board[(columnindex rowindex ) tile board[(columnindex rowindex ) if tile =tile =tile =tile =playertile return true check for four-in- -row going left-down diagonalfour in row |
6,827 | tile board[(columnindex rowindex) tile board[(columnindex rowindex ) tile board[(columnindex rowindex ) tile board[(columnindexrowindex ) if tile =tile =tile =tile =playertile return true return false if the program is run (instead of imported)run the game if __name__ ='__main__' main(after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingcreate three-in- -row or five-in- -row variant make three-player variant of this game add "wildcardtile that randomly drops after the playersturns and can be used by either player add "blocktiles that cannot be used by either player exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change player_o 'oon line to player_o ' ' what happens if you change return (columnindexrowindexon line to return (columnindex ) what happens if you change response ='quiton line to response !'quit' what error message do you get if you change tilechars [on line to tilechars {} project # |
6,828 | guess the number guess the number is classic game for beginners to practice basic programming techniques in this gamethe computer thinks of random number between and the player has chances to guess the number after each guessthe computer tells the player if it was too high or too low |
6,829 | when you run guess pythe output will look like thisguess the numberby al sweigart al@inventwithpython com am thinking of number between and you have guesses left take guess your guess is too high you have guesses left take guess your guess is too low --snip-you have guesses left take guess yayyou guessed my numberhow it works guess the number uses several basic programming conceptsloopsifelse statementsfunctionsmethod callsand random numbers python' random module generates pseudorandom numbers--numbers that look random but are technically predictable pseudorandom numbers are easier for computers to generate than truly random numbersand they're considered "random enoughfor applications such as video games and some scientific simulations python' random module produces pseudorandom numbers from seed valueand each stream of pseudorandom numbers generated from the same seed will be the same for exampleenter the following into the interactive shellimport random random seed( random randint( )random randint( )random randint( if you restart the interactive shell and run this code againit produces the same pseudorandom numbers the video game minecraft generates its pseudorandom virtual worlds from starting seed valuewhich is why different players can re-create the same world by using the same seed """guess the numberby al sweigart al@inventwithpython com try to guess the secret number based on hints view this code at tagstinybeginnergame"" import random project # |
6,830 | def askforguess() while true guess input(''enter the guess if guess isdecimal() return int(guessconvert string guess to an integer print('please enter number between and ' print('guess the numberby al sweigart al@inventwithpython com' print( secretnumber random randint( select random number print(' am thinking of number between and ' for in range( )give the player guesses print('you have {guesses left take guess format( ) guess askforguess( if guess =secretnumber break break out of the for loop if the guess is correct offer hint if guess secretnumber print('your guess is too low ' if guess secretnumber print('your guess is too high ' reveal the results if guess =secretnumber print('yayyou guessed my number!' else print('game over the number was thinking of was'secretnumberafter entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the followingcreate "guess the lettervariant that gives hints based on the alphabetical order of the player' guess make the hints after each guess say "warmeror "colderbased on the player' previous guess exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change input(''on line to input(secretnumber) what error message do you get if you change return int(guesson line to return guessguess the number |
6,831 | random randint( ) what happens if you change format( ion line to format( ) what error message do you get if you change guess =secretnumber on line to guess secretnumber project # |
6,832 | gullible in this short and simple programyou can learn the secret and subtle art of keeping gullible person busy for hours won' spoil the punch line here copy the code and run it for yourself this project is great for beginnerswhether you're smart or not so smart |
6,833 | when you run gullible pythe output will look like thisgullibleby al sweigart al@inventwithpython com do you want to know how to keep gullible person busy for hoursy/ do you want to know how to keep gullible person busy for hoursy/ do you want to know how to keep gullible person busy for hoursy/ yes do you want to know how to keep gullible person busy for hoursy/ yes do you want to know how to keep gullible person busy for hoursy/ tell me how to keep gullible person busy for hours "tell me how to keep gullible person busy for hoursis not valid yes/no response do you want to know how to keep gullible person busy for hoursy/ do you want to know how to keep gullible person busy for hoursy/ do you want to know how to keep gullible person busy for hoursy/ thank you have nice dayhow it works to be more user friendlyyour programs should attempt to interpret range of possible inputs from the user for examplethis program asks the user yes/no questionbut it would be simpler for the player to simply enter "yor "ninstead of enter the full word the program can also understand the player' intent if their caps lock key is activatedbecause it calls the lower(string method on the string the player entered this way' ''yes'' ''yes'and 'yes'are all interpreted the same by the program the same goes for negative response from the player """gullibleby al sweigart al@inventwithpython com how to keep gullible person busy for hours (this is joke program view this code at tagstinybeginnerhumor"" print('gullibleby al sweigart al@inventwithpython com' while truemain program loop print('do you want to know how to keep gullible person busy for hoursy/ ' response input(''get the user' response if response lower(='noor response lower(=' ' break if "no"break out of this loop if response lower(='yesor response lower(=' ' continue if "yes"continue to the start of this loop project # |
6,834 | print('"{}is not valid yes/no response format(response) print('thank you have nice day!'exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change response lower(='noon line to response lower(!'no' what happens if you change while trueon line to while false:gullible |
6,835 | hacking minig ame in this gamethe player must hack computer by guessing seven-letter word used as the secret password the computer' memory banks display the possible wordsand the player is given hints as to how close each guess was for exampleif the secret password is monitor but the player guessed containthey are given the hint that two out of seven letters were correctbecause both monitor and contain have the letter and as their second and third letter this game is similar to project "bagels,and the hacking minigame in the fallout series of video games |
6,836 | when you run hacking pythe output will look like thishacking minigameby al sweigart al@inventwithpython com find the password in the computer' memory $],>@|~~resolve {>+)<!?chicken, }@% -:;/$^(|<|! ][})?#@#address ;)][#?<&~$~+&} ,#=)>{-;/despite %[!]{refugee@?~ }}!-display%% [^%[@}^< +{ @$ =>>,:*%? ?@+{% )?~/)+penalty?- >[,?*#improve@$--snip-enter password( tries remainingresolve access denied ( / correctenter password( tries remainingimprove how it works this game has hacking themebut it doesn' involve any actual computer hacking if we' just listed the possible words on the screenthe gameplay would have been identical howeverthe cosmetic additions that mimic computer' memory banks convey an exciting feeling of computer hacking the attention to detail and user experience turn plainboring game into an exciting one """hacking minigameby al sweigart al@inventwithpython com the hacking mini-game from "fallout find out which seven-letter word is the password by using clues each guess gives you view this code at tagslargeartisticgamepuzzle"" notethis program requires the sevenletterwords txt file you can download it from import randomsys set up the constants the garbage filler characters for the "computer memorydisplay garbage_chars '~!@#$%^&*() +-={}[]|;:?/ load the words list from text file that has -letter words with open('sevenletterwords txt'as wordlistfile words wordlistfile readlines( for in range(len(words)) convert each word to uppercase and remove the trailing newline words[iwords[istrip(upper( hacking minigame |
6,837 | """run single game of hacking "" print('''hacking minigameby al sweigart al@inventwithpython com find the password in the computer' memory you are given clues after each guess for exampleif the secret password is monitor but the player guessed containthey are given the hint that out of letters were correctbecause both monitor and contain have the letter and as their nd and rd letter you get four guesses \ ''' input('press enter to begin ' gamewords getwords( the "computer memoryis just cosmeticbut it looks cool computermemory getcomputermemorystring(gamewords secretpassword random choice(gamewords print(computermemory start at tries remaininggoing down for triesremaining in range( - ) playermove askforplayerguess(gamewordstriesremaining if playermove =secretpassword print(' ' return else nummatches nummatchingletters(secretpasswordplayermove print('access denied ({}/ correct)format(nummatches) print('out of tries secret password was {format(secretpassword) def getwords() """return list of words that could possibly be the password the secret password will be the first word in the list to make the game fairwe try to ensure that there are words with range of matching numbers of letters as the secret word "" secretpassword random choice(words words [secretpassword find two more wordsthese have zero matching letters we use " because the secret password is already in words while len(words randomword getonewordexcept(words if nummatchingletters(secretpasswordrandomword= words append(randomword find two words that have matching letters (but give up at tries if not enough can be found for in range( ) if len(words= break found wordsso break out of the loop randomword getonewordexcept(words if nummatchingletters(secretpasswordrandomword= words append(randomword project # |
6,838 | find at least seven words that have at least one matching letter (but give up at tries if not enough can be found for in range( ) if len(words= break found or more wordsso break out of the loop randomword getonewordexcept(words if nummatchingletters(secretpasswordrandomword! words append(randomword add any random words needed to get words total while len(words randomword getonewordexcept(words words append(randomword assert len(words= return words def getonewordexcept(blocklist=none) """returns random word from words that isn' in blocklist "" if blocklist =none blocklist [ while true randomword random choice(words if randomword not in blocklist return randomword def nummatchingletters(word word ) """returns the number of matching letters in these two words "" matches for in range(len(word )) if word [ =word [ ] matches + return matches def getcomputermemorystring(words) """return string representing the "computer memory"" pick one line per word to contain word there are linesbut they are split into two halves lineswithwords random sample(range( )len(words) the starting memory address (this is also cosmetic memoryaddress random randint( create the "computer memorystring computermemory [will contain stringsone for each line nextword the index in words of the word to put into line for linenum in range( )the "computer memoryhas lines create half line of garbage charactershacking minigame |
6,839 | lefthalf ' righthalf ' for in range( )each half line has characters lefthalf +random choice(garbage_chars righthalf +random choice(garbage_chars fill in the password from words if linenum in lineswithwords find random place in the half line to insert the word insertionindex random randint( insert the word lefthalf (lefthalf[:insertionindexwords[nextword lefthalf[insertionindex :] nextword + update the word to put in the half line if linenum in lineswithwords find random place in the half line to insert the word insertionindex random randint( insert the word righthalf (righthalf[:insertionindexwords[nextword righthalf[insertionindex :] nextword + update the word to put in the half line computermemory append(' xhex(memoryaddress)[ :zfill( lefthalf ' xhex(memoryaddress ( * ))[ :zfill( righthalf memoryaddress + jump fromsay xe to xe each string in the computermemory list is joined into one large string to return return '\njoin(computermemory def askforplayerguess(wordstries) """let the player enter password guess "" while true print('enter password({tries remaining)format(tries) guess input(''upper( if guess in words return guess print('that is not one of the possible passwords listed above ' print('try entering "{}or "{}format(words[ ]words[ ]) if this program was run (instead of imported)run the game if __name__ ='__main__' try main( except keyboardinterrupt sys exit(when ctrl- is pressedend the program project # |
6,840 | experimental changes to it on your ownyou can also try to figure out how to do the followingfind word list on the internet and create your own sevenletterwords txt filemaybe one with sixor eight-letter words create different visualization of the "computer memory exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change for in range( )on line to for in range( ): what happens if you change garbage_chars '~!@#$%^&*() +-={[]|;:?/on line to garbage_chars ' what happens if you change gamewords getwords(on line to gamewords ['malkovich' what error message do you get if you change return words on line to return what happens if you change randomword random choice(wordson line to secretpassword 'password'hacking minigame |
6,841 | hangman and guillotine this classic word game has the player guess the letters to secret word for each incorrect letteranother part of the hangman is drawn try to guess the complete word before the hangman completes the secret words in this version are all animals like rabbit and pigeonbut you can replace these with your own set of words the hangman_pics variable contains ascii-art strings of each step of the hangman' noose+--====+-- ====+-- ====+-- /====+-- /|====+-- /|====+-- /|==== |
6,842 | hangman_pics variable with the following strings depicting guillotine|==|===|===|===|===|/|===|===|/-\|/|===|===|/|||/-\|/|===|===|/|||/-\|\ /|===the program in action when you run hangman pythe output will look like thishangmanby al sweigart al@inventwithpython com +--====the category isanimals missed lettersno missed letters yet guess letter --snip-+-- /====the category isanimals missed lettersa guess letter yesthe secret word isotter you have wonhangman and guillotine |
6,843 | hangman and guillotine share the same game mechanics but have different presentations this makes it easy to swap out the ascii-art noose graphics with the ascii-art guillotine graphics without having to change the main logic that the program follows this separation of the presentation and logic parts of the program makes it easier to update with new features or different designs in professional software developmentthis strategy is an example of software design pattern or software architecturewhich concerns itself with how to structure your programs for easy understanding and modification this is mainly useful in large software applicationsbut you can also apply these principles to smaller projects """hangmanby al sweigart al@inventwithpython com guess the letters to secret word before the hangman is drawn view this code at tagslargegamewordpuzzle"" version of this game is featured in the book "invent your own computer games with python import randomsys set up the constants (!try adding or changing the strings in hangman_pics to make guillotine instead of gallows hangman_pics [ "" +-- =====""" "" +-- =====""" "" +-- =====""" "" +-- project # |
6,844 | =====""" "" +-- /| =====""" "" +-- /| =====""" "" +-- /| =====""" (!try replacing category and words with new strings category 'animals words 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebrasplit( def main() print('hangmanby al sweigart al@inventwithpython com' setup variables for new game missedletters [list of incorrect letter guesses correctletters [list of correct letter guesses secretword random choice(wordsthe word the player must guess while truemain game loop drawhangman(missedletterscorrectletterssecretword let the player enter their letter guess guess getplayerguess(missedletters correctletters if guess in secretword add the correct guess to correctlettershangman and guillotine |
6,845 | correctletters append(guess check if the player has won foundallletters true start off assuming they've won for secretwordletter in secretword if secretwordletter not in correctletters there' letter in the secret word that isn' yet in correctlettersso the player hasn' won foundallletters false break if foundallletters print('yesthe secret word is:'secretword print('you have won!' break break out of the main game loop else the player has guessed incorrectly missedletters append(guess check if player has guessed too many times and lost (the " is because we don' count the empty gallows in hangman_pics if len(missedletters=len(hangman_pics drawhangman(missedletterscorrectletterssecretword print('you have run out of guesses!' print('the word was "{}"format(secretword) break def drawhangman(missedletterscorrectletterssecretword) """draw the current state of the hangmanalong with the missed and correctly-guessed letters of the secret word "" print(hangman_pics[len(missedletters)] print('the category is:'category print( show the incorrectly guessed letters print('missed letters'end='' for letter in missedletters print(letterend=' if len(missedletters= print('no missed letters yet ' print( display the blanks for the secret word (one blank per letter) blanks [' 'len(secretword replace blanks with correctly guessed letters for in range(len(secretword)) if secretword[iin correctletters blanks[isecretword[ show the secret word with spaces in between each letter print(join(blanks) project # |
6,846 | """returns the letter the player entered this function makes sure the player entered single letter they haven' guessed before "" while truekeep asking until the player enters valid letter print('guess letter ' guess input(''upper( if len(guess! print('please enter single letter ' elif guess in alreadyguessed print('you have already guessed that letter choose again ' elif not guess isalpha() print('please enter letter ' else return guess if this program was run (instead of imported)run the game if __name__ ='__main__' try main( except keyboardinterrupt sys exit(when ctrl- is pressedend the program after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingadd "category selectfeature and let the player choose what category of words they want to play add selection feature so the player can choose between the hangman and guillotine versions of the game exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you delete or comment out missedletters append(guesson line what happens if you change drawhangman(missedletterscorrectletterssecretwordon line to drawhangman(correctlettersmissedletterssecretword) what happens if you change [' 'on line to ['*'] what happens if you change print(join(blanks)on line to print(secretword)hangman and guillotine |
6,847 | hex grid this short program produces tessellated image of hexagonal gridsimilar to chicken wire it shows that you don' need lot of code to make something interesting slightly more complicated variation of this program is project "shining carpet note that this program uses raw stringswhich prefix the opening quote with lowercase so that the backslashes in the string aren' interpreted as escape characters |
6,848 | figure - shows what the output will look like when you run hexgrid py figure - output showing tessellated image of hexagonal grid how it works the power behind programming is that it can make computer carry out repetitive instructions quickly and without mistakes this is how dozen lines of code can create hundredsthousandsor millions of hexagons on the screen in the command prompt or terminal windowyou can redirect program' output from the screen to text file on windowsrun py hexgrid py hextiles txt to create text file that contains the hexagons on linux and macosrun python hexgrid py hextiles txt without the size of the screen as limityou can increase the x_repeat and y_repeat constants and save the contents to file from thereit' easy to print the file on papersend it in an emailor post it to social media this applies to any computer-generated artwork you create """hex gridby al sweigart al@inventwithpython com displays simple tessellation of hexagon grid view this code at tagstinybeginnerartistic"" set up the constants (!try changing these values to other numbers x_repeat how many times to tessellate horizontally y_repeat how many times to tessellate vertically hex grid |
6,849 | display the top half of the hexagon for in range(x_repeat) print( '\ 'end='' print( display the bottom half of the hexagon for in range(x_repeat) print( '\ 'end='' print(after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingcreate tiled hexagons of larger size create tiled rectangular bricks instead of hexagons for practicetry re-creating this program with larger hexagon gridssuch as the following patterns\___\___\___\___\___\___\___\___\___\___\___\___\___\___\___\___\___\___\___\\\\\\\\\\exploring the program this is base programso there aren' many options to customize it insteadconsider how you could similarly program patterns of other shapes project # |
6,850 | hourgl ass this visualization program has rough physics engine that simulates sand falling through the small aperture of an hourglass the sand piles up in the bottom half of the hourglassthen the hourglass is turned over so the process repeats |
6,851 | figure - shows what the output will look like when you run hourglass py figure - the output of the hourglass program with sand falling how it works the hourglass program implements rudimentary physics engine physics engine is software that simulates physical objects falling under gravitycolliding with each otherand moving according to the laws of physics you'll find physics engines used in video gamescomputer animationand scientific simulations on lines to each "grainof sand checks if the space beneath it is empty and moves down if it is otherwiseit checks if it can move down and to the left (lines to or down and to the right (lines to of coursethere is much more to kinematicsthe branch of classical physics that deals with the motion of macroscopic objectsthan this howeveryou don' need degree in physics to make primitive simulation of sand in an hourglass that is enjoyable to look at """hourglassby al sweigart al@inventwithpython com an animation of an hourglass with falling sand press ctrl- to stop view this code at tagslargeartisticbextsimulation"" import randomsystime try import bext except importerror print('this program requires the bext modulewhich you' project # |
6,852 | print('can install by following the instructions at' print(' sys exit( set up the constants pause_length (!try changing this to or (!try changing this to any number between and wide_fall_chance screen_width screen_height the index of values in an (xytuple is the index of values in an (xytuple is sand chr( wall chr( set up the walls of the hourglass hourglass set(has (xytuples for where hourglass walls are (!try commenting out some hourglass add(lines to erase walls for in range( ) hourglass add(( )add walls for the top cap of the hourglass hourglass add(( )add walls for the bottom cap for in range( ) hourglass add(( )add walls for the top left straight wall hourglass add(( )add walls for the top right straight wall hourglass add(( )add walls for the bottom left hourglass add(( )add walls for the bottom right for in range( ) hourglass add(( )add the top left slanted wall hourglass add(( )add the top right slanted wall hourglass add(( )add the bottom left slanted wall hourglass add(( )add the bottom right slanted wall set up the initial sand at the top of the hourglass initial_sand set( for in range( ) for in range( ) initial_sand add((xy ) def main() bext fg('yellow' bext clear( draw the quit message bext goto( print('ctrl- to quit 'end='' display the walls of the hourglass for wall in hourglass bext goto(wall[ ]wall[ ] print(wallend='' while truemain program loop allsand list(initial_sandhourglass |
6,853 | draw the initial sand for sand in allsand bext goto(sand[ ]sand[ ] print(sandend='' runhourglasssimulation(allsand def runhourglasssimulation(allsand) """keep running the sand falling simulation until the sand stops moving "" while truekeep looping until sand has run out random shuffle(allsandrandom order of grain simulation sandmovedonthisstep false for isand in enumerate(allsand) if sand[ =screen_height sand is on the very bottomso it won' move continue if nothing is under this sandmove it down nosandbelow (sand[ ]sand[ not in allsand nowallbelow (sand[ ]sand[ not in hourglass canfalldown nosandbelow and nowallbelow if canfalldown draw the sand in its new position down one space bext goto(sand[ ]sand[ ] print('end=''clear the old position bext goto(sand[ ]sand[ print(sandend='' set the sand in its new position down one space allsand[ (sand[ ]sand[ sandmovedonthisstep true else check if the sand can fall to the left belowleft (sand[ sand[ nosandbelowleft belowleft not in allsand nowallbelowleft belowleft not in hourglass left (sand[ sand[ ] nowallleft left not in hourglass notonleftedge sand[ canfallleft (nosandbelowleft and nowallbelowleft and nowallleft and notonleftedge check if the sand can fall to the right belowright (sand[ sand[ nosandbelowright belowright not in allsand nowallbelowright belowright not in hourglass right (sand[ sand[ ] nowallright right not in hourglass notonrightedge sand[xscreen_width canfallright (nosandbelowright and nowallbelowright project # |
6,854 | and nowallright and notonrightedgeset the falling directionfallingdirection none if canfallleft and not canfallrightfallingdirection - set the sand to fall left elif not canfallleft and canfallrightfallingdirection set the sand to fall right elif canfallleft and canfallrightboth are possibleso randomly set itfallingdirection random choice((- )check if the sand can "farfall two spaces to the left or right instead of just one spaceif random random( <wide_fall_chancebelowtwoleft (sand[ sand[ nosandbelowtwoleft belowtwoleft not in allsand nowallbelowtwoleft belowtwoleft not in hourglass notonsecondtoleftedge sand[ canfalltwoleft (canfallleft and nosandbelowtwoleft and nowallbelowtwoleft and notonsecondtoleftedgebelowtworight (sand[ sand[ nosandbelowtworight belowtworight not in allsand nowallbelowtworight belowtworight not in hourglass notonsecondtorightedge sand[xscreen_width canfalltworight (canfallright and nosandbelowtworight and nowallbelowtworight and notonsecondtorightedgeif canfalltwoleft and not canfalltworightfallingdirection - elif not canfalltwoleft and canfalltworightfallingdirection elif canfalltwoleft and canfalltworightfallingdirection random choice((- )if fallingdirection =nonethis sand can' fallso move on continue draw the sand in its new positionbext goto(sand[ ]sand[ ]print('end=''erase old sand bext goto(sand[xfallingdirectionsand[ print(sandend=''draw new sand move the grain of sand to its new positionallsand[ (sand[xfallingdirectionsand[ sandmovedonthisstep true sys stdout flush((required for bext-using programs time sleep(pause_lengthpause after this if no sand has moved on this stepreset the hourglasshourglass |
6,855 | if not sandmovedonthisstep time sleep( erase all of the sand for sand in allsand bext goto(sand[ ]sand[ ] print('end='' break break out of main simulation loop if this program was run (instead of imported)run the game if __name__ ='__main__' try main( except keyboardinterrupt sys exit(when ctrl- is pressedend the program after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingcreate wall shapes other than an hourglass create points on the screen that continuously pour out new grains of sand exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change range( on line to range( ) what happens if you change range( on line to range( ) what happens if you change sandmovedonthisstep false on line to sandmovedonthisstep true what happens if you change fallingdirection none on line to fallingdirection what happens if you change random random( <wide_fall_chance on line to random random( <wide_fall_chance project # |
6,856 | hungry robots you are trapped in maze with hungry robotsyou don' know why robots need to eatbut you don' want to find out the robots are badly programmed and will move directly toward youeven if blocked by walls you must trick the robots into crashing into each other (or dead robotswithout being caught you have personal teleporter device that can send you to random new placebut it only has enough battery for two trips alsoyou and the robots can slip through corners |
6,857 | when you run hungryrobots pythe output will look like thishungry robotsby al sweigart al@inventwithpython com --snip-####################################### ## ### ######rx## ##### ### ##rr #rr #rrr ## #######################################( )eleports remaining ( ( ( ( (denter move or quit( ( --snip-how it works the xand ycartesian coordinates that represent positions in this game allow us to use math to determine the direction in which the robots should move in programmingx-coordinates increase going rightand -coordinates increase going down this means that if the robot' -coordinate is larger than the player' coordinateit should move left (that isthe code should subtract from its current -coordinateto move closer to the player if the robot' -coordinate is smallerit should move right (that isthe code should add to its current -coordinateinstead the same applies to moving up and down based on their relative -coordinates """hungry robotsby al sweigart al@inventwithpython com escape the hungry robots by making them crash into each other view this code at tagslargegame"" import randomsys set up the constants project # |
6,858 | (!try changing this to or height (!try changing this to num_robots (!try changing this to or num_teleports (!try changing this to or num_dead_robots (!try changing this to or num_walls (!try changing this to or empty_space (!try changing this to player '@(!try changing this to ' robot ' (!try changing this to '@ dead_robot ' (!try changing this to ' (!try changing this to '#or 'oor ' wall chr( character is '# def main() print('''hungry robotsby al sweigart al@inventwithpython com you are trapped in maze with hungry robotsyou don' know why robots need to eatbut you don' want to find out the robots are badly programmed and will move directly toward youeven if blocked by walls you must trick the robots into crashing into each other (or dead robots without being caught you have personal teleporter devicebut it only has enough battery for {trips keep in mindyou and robots can slip through the corners of two diagonal walls ''format(num_teleports) input('press enter to begin ' set up new game board getnewboard( robots addrobots(board playerposition getrandomemptyspace(boardrobots while truemain game loop displayboard(boardrobotsplayerposition if len(robots= check if the player has won print('all the robots have crashed into each other and you' print('lived to tell the talegood job!' sys exit( move the player and robots playerposition askforplayermove(boardrobotsplayerposition robots moverobots(boardrobotsplayerposition for xy in robotscheck if the player has lost if (xy=playerposition displayboard(boardrobotsplayerposition print('you have been caught by robot!' sys exit( def getnewboard() """returns dictionary that represents the board the keys are hungry robots |
6,859 | (xytuples of integer indexes for board positionsthe values are wallempty_spaceor dead_robot the dictionary also has the key 'teleportsfor the number of teleports the player has left the living robots are stored separately from the board dictionary "" board {'teleports'num_teleports create an empty board for in range(width) for in range(height) board[(xy)empty_space add walls on the edges of the board for in range(width) board[( )wall make top wall board[(xheight )wall make bottom wall for in range(height) board[( )wall make left wall board[(width )wall make right wall add the random walls for in range(num_walls) xy getrandomemptyspace(board[] board[(xy)wall add the starting dead robots for in range(num_dead_robots) xy getrandomemptyspace(board[] board[(xy)dead_robot return board def getrandomemptyspace(boardrobots) """return (xyinteger tuple of an empty space on the board "" while true randomx random randint( width randomy random randint( height if isempty(randomxrandomyboardrobots) break return (randomxrandomy def isempty(xyboardrobots) """return true if the (xyis empty on the board and there' also no robot there "" return board[(xy)=empty_space and (xynot in robots def addrobots(board) """add num_robots number of robots to empty spaces on the board and return list of these (xyspaces where robots are now located "" robots [ for in range(num_robots) xy getrandomemptyspace(boardrobots robots append((xy) return robots project # |
6,860 | def displayboard(boardrobotsplayerposition) """display the boardrobotsand player on the screen "" loop over every space on the board for in range(height) for in range(width) draw the appropriate character if board[(xy)=wall print(wallend='' elif board[(xy)=dead_robot print(dead_robotend='' elif (xy=playerposition print(playerend='' elif (xyin robots print(robotend='' else print(empty_spaceend='' print(print newline def askforplayermove(boardrobotsplayerposition) """returns the (xyinteger tuple of the place the player moves nextgiven their current location and the walls of the board "" playerxplayery playerposition find which directions aren' blocked by wall 'qif isempty(playerx playery boardrobotselse 'wif isempty(playerx playery boardrobotselse 'eif isempty(playerx playery boardrobotselse 'dif isempty(playerx playery boardrobotselse 'cif isempty(playerx playery boardrobotselse 'xif isempty(playerx playery boardrobotselse 'zif isempty(playerx playery boardrobotselse 'aif isempty(playerx playery boardrobotselse allmoves ( ' ' while true get player' move print('( )eleports remaining{}format(board["teleports"]) print(({}({}({})format(qwe) print(({}( ({})format(ad) print('enter move or quit({}({}({})format(zxc) move input(''upper( if move ='quit' print('thanks for playing!' sys exit( elif move ='tand board['teleports' teleport the player to random empty space board['teleports'- return getrandomemptyspace(boardrobots elif move !'and move in allmoves return the new player position based on their move return {' '(playerx playery )hungry robots |
6,861 | ' '(playerx playery ) ' '(playerx playery ) ' '(playerx playery ) ' '(playerx playery ) ' '(playerx playery ) ' '(playerx playery ) ' '(playerx playery ) ' '(playerxplayery)}[move def moverobots(boardrobotpositionsplayerposition) """return list of (xytuples of new robot positions after they have tried to move toward the player "" playerxplayery playerposition nextrobotpositions [ while len(robotpositions robotxroboty robotpositions[ determine the direction the robot moves if robotx playerx movex move right elif robotx playerx movex - move left elif robotx =playerx movex don' move horizontally if roboty playery movey move up elif roboty playery movey - move down elif roboty =playery movey don' move vertically check if the robot would run into walland adjust course if board[(robotx movexroboty movey)=wall robot would run into wallso come up with new move if board[(robotx movexroboty)=empty_space movey robot can' move horizontally elif board[(robotxroboty movey)=empty_space movex robot can' move vertically else robot can' move movex movey newrobotx robotx movex newroboty roboty movey if (board[(robotxroboty)=dead_robot or board[(newrobotxnewroboty)=dead_robot) robot is at crash siteremove it del robotpositions[ continue check if it moves into robotthen destroy both robots project # |
6,862 | if (newrobotxnewrobotyin nextrobotpositions board[(newrobotxnewroboty)dead_robot nextrobotpositions remove((newrobotxnewroboty) else nextrobotpositions append((newrobotxnewroboty) remove robots from robotpositions as they move del robotpositions[ return nextrobotpositions if this program was run (instead of imported)run the game if __name__ ='__main__' main(after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the followingcreate two different kinds of robotsthose that can only move diagonally and those that can only move in cardinal directions give the player limited number of traps they can leave behind to stop any robot that steps on one give the player limited number of "instant wallsthat they can put up for their own defense exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change wall chr( on line to wall ' ' what happens if you change return nextrobotpositions on line to return robotpositions what happens if you delete or comment out displayboard(boardrobotsplayerpositionon line what happens if you delete or comment out robots moverobots(boardrobotsplayerpositionon line hungry robots |
6,863 | ' you are the world-famous detective mathilde camus zophie the cat has gone missingand you must sift through the clues suspects either always tell lies or always tell the truth will you find zophie the cat in time and accuse the guilty partyin this gameyou take taxi to different locations around the city at each location is suspect and an item you can ask suspects about other suspects and itemscompare their answers with your own exploration notesand determine if they are lying or telling the truth some will know who has catnapped zophie (or where she isor what item is found at the location of the kidnapper)but you must determine if you can believe them you have five minutes to find the criminal but will lose if you make three wrong accusations this game is inspired by homestar runner' "where' an egg?game |
6,864 | when you run jaccuse pythe output will look like thisj'accuse( mystery game--snip-time left min sec you are in your taxi where do you want to go( )lbino alligator pit ( )owling alley ( )ity hall ( )uck pond ( )ipster cafe ( )ld barn ( )niversity library ( )ideo game museum ( )oo time left min sec you are at the albino alligator pit espressa toffeepot with the one cowboy boot is here ( " 'accuse!( accusations left(zask if they know where zophie the cat is (tgo back to the taxi ( ask about espressa toffeepot ( ask about one cowboy boot they give you this clue"duke hautdogpress enter to continue --snip-how it works to fully understand this programyou should pay close attention to the clues dictionarywhich is set up on lines to you can uncomment lines to to display it on the screen this dictionary has strings from the suspects list for the keys and "clue dictionariesfor the values each of these clue dictionaries contains strings from suspects and items the original suspect will answer with these strings when asked about another suspect or item for exampleif clues['duke hautdog']['candlestick'is set to 'duck pond'then when the player asks duke hautdog about the candlestickthey'll say it is at the duck pond the suspectsitemslocationsand culprit get shuffled each time the game is played the code for this program revolves around this data structureso understanding it is necessary to unlocking your understanding of the rest of the program """ 'accuse!by al sweigart al@inventwithpython com mystery game of intrigue and missing cat view this code at 'accuse |
6,865 | play the original flash game at more info at import timerandomsys set up the constants suspects ['duke hautdog''maximum powers''bill monopolis''senator schmear''mrs feathertoss''dr jean splicer''raffles the clown''espressa toffeepot''cecil edgar vanderton' items ['flashlight''candlestick''rainbow flag''hamster wheel''anime vhs tape''jar of pickles''one cowboy boot''clean underpants'' dollar gift card' places ['zoo''old barn''duck pond''city hall''hipster cafe''bowling alley''video game museum''university library''albino alligator pit' time_to_solve seconds ( minutesto solve the game first letters and longest length of places are needed for menu display place_first_letters { longest_place_name_length for place in places place_first_letters[place[ ]place if len(placelongest_place_name_length longest_place_name_length len(place basic sanity checks of the constants assert len(suspects= assert len(items= assert len(places= first letters must be unique assert len(place_first_letters keys()=len(places knownsuspectsanditems [ visitedplaceskeys=placesvalues=strings of the suspect item there visitedplaces { currentlocation 'taxistart the game at the taxi accusedsuspects [accused suspects won' offer clues liars random sample(suspectsrandom randint( ) accusationsleft you can accuse up to people culprit random choice(suspects common indexes link thesee suspects[ and items[ are at places[ random shuffle(suspects random shuffle(items random shuffle(places create data structures for clues the truth-tellers give about each item and suspect clueskeys=suspects being asked for cluevalue="clue dictionary clues { for iinterviewee in enumerate(suspects) if interviewee in liars continue skip the liars for now project # |
6,866 | this "clue dictionaryhas keys=items suspects value=the clue given clues[interviewee{ clues[interviewee]['debug_liar'false useful for debugging for item in itemsselect clue about each item if random randint( = tells where the item is clues[interviewee][itemplaces[items index(item) elsetells who has the item clues[interviewee][itemsuspects[items index(item) for suspect in suspectsselect clue about each suspect if random randint( = tells where the suspect is clues[interviewee][suspectplaces[suspects index(suspect) elsetells what item the suspect has clues[interviewee][suspectitems[suspects index(suspect) create data structures for clues the liars give about each item and suspect for iinterviewee in enumerate(suspects) if interviewee not in liars continue we've already handled the truth-tellers this "clue dictionaryhas keys=items suspects value=the clue given clues[interviewee{ clues[interviewee]['debug_liar'true useful for debugging this interviewee is liar and gives wrong clues for item in items if random randint( = while trueselect random (wrongplace clue lies about where the item is clues[interviewee][itemrandom choice(places if clues[interviewee][item!places[items index(item)] break out of the loop when wrong clue is selected break else while trueselect random (wrongsuspect clue clues[interviewee][itemrandom choice(suspects if clues[interviewee][item!suspects[items index(item)] break out of the loop when wrong clue is selected break for suspect in suspects if random randint( = while trueselect random (wrongplace clue clues[interviewee][suspectrandom choice(places if clues[interviewee][suspect!places[items index(item)] break out of the loop when wrong clue is selected break else while trueselect random (wrongitem clue clues[interviewee][suspectrandom choice(items if clues[interviewee][suspect!items[suspects index(suspect)] break out of the loop when wrong clue is selected break 'accuse |
6,867 | create the data structures for clues given when asked about zophie zophieclues { for interviewee in random sample(suspectsrandom randint( )) kindofclue random randint( if kindofclue = if interviewee not in liars they tell you who has zophie zophieclues[intervieweeculprit elif interviewee in liars while true select (wrongsuspect clue zophieclues[intervieweerandom choice(suspects if zophieclues[interviewee!culprit break out of the loop when wrong clue is selected break elif kindofclue = if interviewee not in liars they tell you where zophie is zophieclues[intervieweeplaces[suspects index(culprit) elif interviewee in liars while true select (wrongplace clue zophieclues[intervieweerandom choice(places if zophieclues[interviewee!places[suspects index(culprit)] break out of the loop when wrong clue is selected break elif kindofclue = if interviewee not in liars they tell you what item zophie is near zophieclues[intervieweeitems[suspects index(culprit) elif interviewee in liars while true select (wrongitem clue zophieclues[intervieweerandom choice(items if zophieclues[interviewee!items[suspects index(culprit)] break out of the loop when wrong clue is selected break experimentuncomment this code to view the clue data structures #import pprint #pprint pprint(clues #pprint pprint(zophieclues #print('culprit ='culprit start of the game print(""" 'accuse( mystery game)" by al sweigart al@inventwithpython com inspired by homestar runner\' "where\' an egg?game you are the world-famous detective mathilde camus zophie the cat has gone missingand you must sift through the clues suspects either always tell liesor always tell the truth ask them about other peopleplacesand items to see if the details they give are project # |
6,868 | their clue about zophie the cat is true or not will you find zophie the cat in time and accuse the guilty party """ input('press enter to begin ' starttime time time( endtime starttime time_to_solve while truemain game loop if time time(endtime or accusationsleft = handle "game overcondition if time time(endtime print('you have run out of time!' elif accusationsleft = print('you have accused too many innocent people!' culpritindex suspects index(culprit print('it was {at the {with the {who catnapped her!format(culpritplaces[culpritindex]items[culpritindex]) print('better luck next timedetective ' sys exit( print( minutesleft int(endtime time time()/ secondsleft int(endtime time time() print('time left{min{secformat(minutesleftsecondsleft) if currentlocation ='taxi' print(you are in your taxi where do you want to go?' for place in sorted(places) placeinfo ' if place in visitedplaces placeinfo visitedplaces[place namelabel '(place[ ')place[ : spacing (longest_place_name_length len(place) print('{{}{}format(namelabelspacingplaceinfo) print('( )uit game' while truekeep asking until valid response is given response input(''upper( if response ='' continue ask again if response =' ' print('thanks for playing!' sys exit( if response in place_first_letters keys() break currentlocation place_first_letters[response continue go back to the start of the main game loop at placeplayer can ask for clues print(you are at the {format(currentlocation) currentlocationindex places index(currentlocation thepersonhere suspects[currentlocationindex theitemhere items[currentlocationindexj'accuse |
6,869 | print({with the {is here format(thepersonheretheitemhere)add the suspect and item at this place to our list of known suspects and itemsif thepersonhere not in knownsuspectsanditemsknownsuspectsanditems append(thepersonhereif items[currentlocationindexnot in knownsuspectsanditemsknownsuspectsanditems append(items[currentlocationindex]if currentlocation not in visitedplaces keys()visitedplaces[currentlocation'({}{})format(thepersonhere lower()theitemhere lower()if the player has accused this person wrongly beforethey won' give cluesif thepersonhere in accusedsuspectsprint('they are offended that you accused them,'print('and will not help with your investigation 'print('you go back to your taxi 'print(input('press enter to continue 'currentlocation 'taxicontinue go back to the start of the main game loop display menu of known suspects items to ask aboutprint(print('( " \'accuse!({accusations left)format(accusationsleft)print('(zask if they know where zophie the cat is 'print('(tgo back to the taxi 'for isuspectoritem in enumerate(knownsuspectsanditems)print('({}ask about {}format( suspectoritem)while truekeep asking until valid response is given response input(''upper(if response in 'jztor (response isdecimal(and int(response<len(knownsuspectsanditems))break if response =' 'player accuses this suspect accusationsleft - use up an accusation if thepersonhere =culprityou've accused the correct suspect print('you\'ve cracked the casedetective!'print('it was {who had catnapped zophie the cat format(culprit)minutestaken int(time time(starttime/ secondstaken int(time time(starttime print('good jobyou solved it in {min{sec format(minutestakensecondstaken)sys exit(elseyou've accused the wrong suspect accusedsuspects append(thepersonhereprint('you have accused the wrong persondetective!'print('they will not help you with anymore clues 'print('you go back to your taxi 'currentlocation 'taxiproject # |
6,870 | elif response =' 'player asks about zophie if thepersonhere not in zophiecluesprint('" don\' know anything about zophie the cat "'elif thepersonhere in zophiecluesprint(they give you this clue"{}"format(zophieclues[thepersonhere])add non-place clues to the list of known thingsif zophieclues[thepersonherenot in knownsuspectsanditems and zophieclues[thepersonherenot in placesknownsuspectsanditems append(zophieclues[thepersonhere]elif response =' 'player goes back to the taxi currentlocation 'taxicontinue go back to the start of the main game loop elseplayer asks about suspect or item thingbeingaskedabout knownsuspectsanditems[int(response if thingbeingaskedabout in (thepersonheretheitemhere)print(they give you this clue"no comment "'elseprint(they give you this clue"{}"format(clues[thepersonhere][thingbeingaskedabout])add non-place clues to the list of known thingsif clues[thepersonhere][thingbeingaskedaboutnot in knownsuspectsanditems and clues[thepersonhere][thingbeingaskedaboutnot in placesknownsuspectsanditems append(clues[thepersonhere][thingbeingaskedabout]input('press enter to continue 'exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change time_to_solve on line to time_to_ solve what happens if you change time time(endtime or accusationsleft = on line to time time(endtime and accusationsleft = what happens if you change place[ :on line to place what happens if you change starttime time_to_solve on line to starttime time_to_solvej'accuse |
6,871 | ' langton' ant is cellular automata simulation on two-dimensional gridsimilar to project "conway' game of life in the simulationan "antbegins on square that is one of two colors if the space is the first colorthe ant switches it to the second colorturns degrees to the rightand moves forward one space if the space is the second colorthe ant switches it to the first colorturns degrees to the leftand moves forward one space despite the very simple set of rulesthe simulation displays complex emergent behavior simulations can feature multiple ants in the same spacecausing interesting interactions when they cross paths with each other langton' ant was invented by computer scientist chris langton in more information about langton' ant can be found at langton% s_ant |
6,872 | figure - shows what the output will look like when you run langtonsant py figure - the hypnotic output of the langton' ant cellular automata how it works this program uses two senses of "direction on the one handthe dictionaries that represent each ant store cardinal directionsnorthsoutheastand west howeverturning left or right (or counterclockwise and clockwisesince we are viewing the ants from aboveis rotational direction ants are supposed to turn left or right in response to the tile they're standing onso lines to set new cardinal direction based on the ant' current cardinal direction and the direction they are turning """langton' antby al sweigart al@inventwithpython com cellular automata animation press ctrl- to stop more info view this code at tagslargeartisticbextsimulation"" import copyrandomsystime try import bext except importerror print('this program requires the bext modulewhich you' print('can install by following the instructions at' print(' sys exit( langton' ant |
6,873 | widthheight bext size( we can' print to the last column on windows without it adding newline automaticallyso reduce the width by one width - height - adjustment for the quit message at the bottom number_of_ants (!try changing this to or pause_amount (!try changing this to or (!try changing these to make the ants look different ant_up '^ ant_down ' ant_left '< ant_right '> (!try changing these colors to one of 'black''red''green' 'yellow''blue''purple''cyan'or 'white(these are the only colors that the bext module supports ant_color 'red black_tile 'black white_tile 'white north 'north south 'south east 'east west 'west def main() bext fg(ant_colorthe antscolor is the foreground color bext bg(white_tileset the background to white to start bext clear( create new board data structure board {'width'width'height'height create ant data structures ants [ for in range(number_of_ants) ant ' 'random randint( width ) ' 'random randint( height ) 'direction'random choice([northsoutheastwest]) ants append(ant keep track of which tiles have changed and need to be redrawn on the screen changedtiles [ while truemain program loop displayboard(boardantschangedtiles changedtiles [ project # |
6,874 | nextboard is what the board will look like on the next step in the simulation start with copy of the current step' board nextboard copy copy(board run single simulation step for each ant for ant in ants if board get((ant[' ']ant[' '])false=true nextboard[(ant[' ']ant[' '])false turn clockwise if ant['direction'=north ant['direction'east elif ant['direction'=east ant['direction'south elif ant['direction'=south ant['direction'west elif ant['direction'=west ant['direction'north else nextboard[(ant[' ']ant[' '])true turn counter clockwise if ant['direction'=north ant['direction'west elif ant['direction'=west ant['direction'south elif ant['direction'=south ant['direction'east elif ant['direction'=east ant['direction'north changedtiles append((ant[' ']ant[' ']) move the ant forward in whatever direction it' facing if ant['direction'=north ant[' '- if ant['direction'=south ant[' '+ if ant['direction'=west ant[' '- if ant['direction'=east ant[' '+ if the ant goes past the edge of the screen it should wrap around to other side ant[' 'ant[' 'width ant[' 'ant[' 'height changedtiles append((ant[' ']ant[' ']) board nextboard def displayboard(boardantschangedtiles) """displays the board and ants on the screen the changedtiles argument is list of (xytuples for tiles on the screen that have changed and need to be redrawn "" langton' ant |
6,875 | draw the board data structure for xy in changedtiles bext goto(xy if board get((xy)false) bext bg(black_tile else bext bg(white_tile antishere false for ant in ants if (xy=(ant[' ']ant[' ']) antishere true if ant['direction'=north print(ant_upend='' elif ant['direction'=south print(ant_downend='' elif ant['direction'=east print(ant_leftend='' elif ant['direction'=west print(ant_rightend='' break if not antishere print('end='' display the quit message at the bottom of the screen bext goto( height bext bg(white_tile print('press ctrl- to quit 'end='' sys stdout flush((required for bext-using programs time sleep(pause_amount if this program was run (instead of imported)run the game if __name__ ='__main__' try main( except keyboardinterrupt print("langton' antby al sweigart al@inventwithpython com" sys exit(when ctrl- is pressedend the program after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make on your ownyou can also try to figure out how to do the following project # let the player load and save the state of the board' tiles from and to text file create additional tile states with new rules of movement and see what behavior emerges implement some of the ideas suggested in the wikipedia article for langton' ant |
6,876 | try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change print('end=''on line to print('end='') what happens if you change ant[' '+ on line to ant[' '- what happens if you change nextboard[(ant[' ']ant[' '])false on line to nextboard[(ant[' ']ant[' '])true what happens if you change width - on line to width - what happens if you change board nextboard on line to board boardlangton' ant |
6,877 | leetspeak there' no better way to demonstrate your mad hacker skills than by replacing letters in your text with numbersm llz!!this word program automatically converts plain english into leetspeakthe coolest way to talk online or at least it was in it takes while to get used tobut with some practiceyou'll eventually be able to read leetspeak fluently for example +@]< |-| le + | | | | | (an \/ nt| |/-\lly | $peak phl| | +ly leetspeak may be hard to read at firstbut the program itself is simple and good for beginners more information about leetspeak can be found at |
6,878 | when you run leetspeak pythe output will look like thisl ](leetspeekby al sweigart al@inventwithpython com enter your leet messagei am leet hacker fear my mad skills the were over two decades ago @ @(]<er ph @ my |$ |ll+ ver tw (ad (copied leetspeak to clipboard how it works the dictionary in the charmapping variable on line maps plain english characters to leetspeak characters howeversince there can be multiple possible leetspeak characters (such as ' or '+for the letter ' ')each value in the charmapping dictionary is list of strings when creating the new leetspeak stringthe program has percent chance of simply using the character in the original english message and percent chance of using one of the leetspeak characters this means the same english message has multiple possible leetspeak translations """leetspeakby al sweigart al@inventwithpython com translates english messages into ] view this code at tagstinybeginnerword"" import random try import pyperclip pyperclip copies text to the clipboard except importerror pass if pyperclip is not installeddo nothing it' no big deal def main() print(''' ](leetspeek by al sweigart al@inventwithpython com enter your leet message:''' english input('' print( leetspeak englishtoleetspeak(english print(leetspeak try trying to use pyperclip will raise nameerror exception if it wasn' imported pyperclip copy(leetspeak print('(copied leetspeak to clipboard )'leetspeak |
6,879 | except nameerror pass do nothing if pyperclip wasn' installed def englishtoleetspeak(message) """convert the english string in message and return leetspeak "" make sure all the keys in `charmappingare lowercase charmapping ' '[' ''@''/-\\']' '['(']' '['|)']' '[' '] ' '['ph']' '[']-[''|-|']' '[' ''!''|']' '[']<'] ' '[' ']' '['$'' ']' '[' ''+']' '['| |'] ' '['\\/'] leetspeak ' for char in messagecheck each character there is chance we change the character to leetspeak if char lower(in charmapping and random random(< possibleleetreplacements charmapping[char lower() leetreplacement random choice(possibleleetreplacements leetspeak leetspeak leetreplacement else don' translate this character leetspeak leetspeak char return leetspeak if this program was run (instead of imported)run the game if __name__ ='__main__' main(after entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the followingmodify the charmapping dictionary so that it supports new leetspeak characters add feature that can convert leetspeak back into plain english exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change return leetspeak on line to return message what happens if you change char lower(on line to char what happens if you change char lower(on line to char upper() what happens if you change leetspeak leetspeak leetreplacement on line to leetspeak leetreplacement project # |
6,880 | ta in this push-your-luck gameyou roll dice to collect stars the more you rollthe more stars you can getbut if you get three skulls you lose everythingthis quick multiplayer game can support as many players as you wantmaking it ideal for parties on your turnyou pull three random dice from the dice cup and roll them you can roll starsskullsand question marks if you end your turnyou get one point per star if you choose to roll againyou keep the question marks and pull new dice to replace the stars and skulls if you collect three skullsyou lose all your stars and end your turn when player gets pointseveryone else gets one more turn before the game ends whoever has the most points wins there are six gold dicefour silver diceand three bronze dice in the cup gold dice have more starsbronze dice have more skullsand silver is even |
6,881 | when you run luckystars pythe output will look like thislucky starsby al sweigart al@inventwithpython com --snip-scoresalice= bob= it is alice' turn +++, 'ooooooo`oooo' +++gold gold bronze stars collected skulls collected do you want to roll againy/ +++___ , 'ooooooo|(()`oooo' vvv +++gold bronze bronze stars collected skulls collected do you want to roll againy/ --snip-how it works the text-based graphics in this program are stored as strings in list in the star_faceskull_faceand question_face variables this format makes them easy to write in code editorwhile the code in lines to display them on the screen note that because three dice are shown togetherthis code must print each horizontal row of text on die face at time simply running code like print(star_facewould result in each of the three dice appearing on top of each otherinstead of side by side """lucky starsby al sweigart al@inventwithpython com "press your luckgame where you roll dice to gather as many stars as possible you can roll as many times as you wantbut if you roll three skulls you lose all your stars inspired by the zombie dice game from steve jackson games view this code at tagslargegamemultiplayer"" import random project # |
6,882 | set up the constants gold 'gold silver 'silver bronze 'bronze star_face ["++" "|" ", |" "'ooooooo|" "`ooo|" " ' |" "++" skull_face ['++' '___ |' '\|' '|(()|' '\|' 'vvv |' '++' question_face ['++' '|' '|' '|' '|' '|' '++' face_width face_height print("""lucky starsby al sweigart al@inventwithpython com "press your luckgame where you roll dice with starsskullsand question marks on your turnyou pull three random dice from the dice cup and roll them you can roll starsskullsand question marks you can end your turn and get one point per star if you choose to roll againyou keep the question marks and pull new dice to replace the stars and skulls if you collect three skullsyou lose all your stars and end your turn when player gets pointseveryone else gets one more turn before the game ends whoever has the most points wins there are gold dice silver diceand bronze dice in the cup gold dice have more starsbronze dice have more skullsand silver is even """ print('how many players are there?' while trueloop until the user enters number response input('' if response isdecimal(and int(response numplayers int(response break lucky stars |
6,883 | print('please enter number larger than ' playernames [list of strings of player names playerscores {keys are player namesvalues are integer scores for in range(numplayers) while truekeep looping until name is entered print('what is player #str( '\' name?' response input('' if response !'and response not in playernames playernames append(response playerscores[response break print('please enter name ' print( turn the player at playernames[ will go first (!uncomment to let player named 'alstart with three points #playerscores['al' endgamewith none while truemain game loop display everyone' score print( print('scores'end='' for iname in enumerate(playernames) print(name str(playerscores[name])end='' if !len(playernames all but the last player have commas separating their names print(''end='' print('\ ' start the number of collected stars and skulls at stars skulls cup has gold silverand bronze dice cup ([gold ([silver ([bronze hand [your hand starts with no dice print('it is playernames[turn'\' turn ' while trueeach iteration of this loop is rolling the dice print( check that there' enough dice left in the cup if ( len(hand)len(cup) end this turn because there are not enough dice print('there aren\' enough dice left in the cup to 'continue playernames[turn'\' turn ' break pull dice from the cup until you have in your hand random shuffle(cupshuffle the dice in the cup while len(hand hand append(cup pop() roll the dice rollresults [ for dice in hand project # |
6,884 | roll random randint( if dice =goldroll gold die ( stars questions skull)if <roll < rollresults append(star_facestars + elif <roll < rollresults append(question_faceelserollresults append(skull_faceskulls + if dice =silverroll silver die ( stars questions skulls)if <roll < rollresults append(star_facestars + elif <roll < rollresults append(question_faceelserollresults append(skull_faceskulls + if dice =bronzeroll bronze die ( star questions skulls)if roll = rollresults append(star_facestars + elif <roll < rollresults append(question_faceelserollresults append(skull_faceskulls + display roll resultsfor linenum in range(face_height)for dicenum in range( )print(rollresults[dicenum][linenum'end=''print(print newline display the type of dice each one is (goldsilverbronze)for dicetype in handprint(dicetype center(face_width'end=''print(print newline print('stars collected:'starsskulls collected:'skullscheck if they've collected or more skullsif skulls > print(' or more skulls means you\'ve lost your stars!'input('press enter to continue 'break print(playernames[turn'do you want to roll againy/ 'while truekeep asking the player until they enter or nresponse input(''upper(if response !'and response[ in (' '' ')lucky stars |
6,885 | break print('please enter yes or no ' if response startswith(' ') print(playernames[turn]'got'stars'stars!' add stars to this player' point total playerscores[playernames[turn]+stars check if they've reached or more points (!try changing this to or points if (endgamewith =none and playerscores[playernames[turn]> ) since this player reached pointsplay one more round for all other players print('\ \ ('! ) print(playernames[turnhas reached points!!!' print('everyone else will get one more turn!' print(('! '\ \ ' endgamewith playernames[turn input('press enter to continue ' break discard the stars and skullsbut keep the question marks nexthand [ for in range( ) if rollresults[ =question_face nexthand append(hand[ ]keep the question marks hand nexthand move on to the next player' turn turn (turn numplayers if the game has endedbreak out of this loop if endgamewith =playernames[turn] break end the game print('the game has ended ' display everyone' score print( print('scores'end='' for iname in enumerate(playernames) print(name str(playerscores[name])end='' if !len(playernames all but the last player have commas separating their names print(''end='' print('\ ' find out who the winners are highestscore winners [ for namescore in playerscores items() if score highestscore this player has the highest score highestscore score project # |
6,886 | winners [nameoverwrite any previous winners elif score =highestscore this player is tied with the highest score winners append(name if len(winners= there is only one winner print('the winner is winners[ '!!!' else there are multiple tied winners print('the winners are'join(winners) print('thanks for playing!'after entering the source code and running it few timestry making experimental changes to it the comments marked with (!have suggestions for small changes you can make exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you delete or comment out random shuffle(cupon line what happens if you change skulls > on line to skulls what error message do you get if you change (turn numplayers on line to (turn ) what happens if you change endgamewith none on line to endgamewith playernames[ ] what happens if you delete or comment out break on line what happens if you change playerscores[response on line to playerscores[response lucky stars |
6,887 | magic fort une ball the magic fortune ball can predict the future and answer your yes/no questions with percent accuracy using the power of python' random number module this program is similar to magic ball toyexcept you don' have to shake it it also features function for slowly printing text strings with spaces in between each charactergiving the messages spookymysterious effect most of the code is dedicated to setting the eerie atmosphere the program itself simply selects message to display in response to random number |
6,888 | when you run magicfortuneball pythe output will look like thism isn' fortune telling just scam to trick money out of gullible peoplel how it works the only thing the magic fortune ball actually does is display randomly chosen string it completely ignores the user' question sureline calls input('')but it doesn' store the return value in any variable because the program doesn' actually use this text letting users enter their questions gives them the sense that the program has an aura of clairvoyance the slowspaceprint(function displays the uppercase text with any letter in lowercasemaking the message look unique the function also inserts spaces between each character of the string and then displays them slowlywith pauses program doesn' need to be sophisticated enough to predict the future to be fun """magic fortune ballby al sweigart al@inventwithpython com ask yes/no question about your future inspired by the magic ball view this code at tagstinybeginnerhumor"" import randomtime def slowspaceprint(textinterval= ) """slowly display text with spaces in between each letter and lowercase letter ' "" for character in text if character =' ' ' are displayed in lowercase for style print(' 'end=''flush=true else all other characters are displayed normally print(character 'end=''flush=true time sleep(interval print(print two newlines at the end print( magic fortune ball |
6,889 | prompt for question slowspaceprint('magic fortune ballby al sweigart' time sleep( slowspaceprint('ask me your yes/no question ' input('' display brief reply replies 'let me think on this ' 'an interesting question ' 'hmmm are you sure you want to know ?' 'do you think some things are best left unknown ?' ' might tell youbut you might not like the answer ' 'yes no maybe will think on it ' 'and what will you do when you know the answerwe shall see ' ' shall consult my visions ' 'you may want to sit down for this ' slowspaceprint(random choice(replies) dramatic pause slowspaceprint(random randint( ) give the answer slowspaceprint(' have an answer ' time sleep( answers 'yesfor sure' 'my answer is no' 'ask me later' ' am programmed to say yes' 'the stars say yesbut say no' ' dunno maybe' 'focus and ask once more' 'doubtfulvery doubtful' 'affirmative' 'yesthough you may not like it' 'nobut you may wish it was so' slowspaceprint(random choice(answers) after entering the source code and running it few timestry making experimental changes to it on your ownyou can also try to figure out how to do the following project # check that the player' question ends in question mark add other answers the program can give |
6,890 | try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change random randint( on line to random randint( ) what error do you get if you change time sleep( on line to time sleep(- )magic fortune ball |
6,891 | mancal the board game mancala is at least , years oldmaking it almost as old as project "royal game of ur it is "seed-sowinggame in which two players select pockets of seeds to spread across the other pockets on the board while trying to collect as many in their store as possible there are several variants of this game across different cultures the name comes from the arab word naqalameaning "to move to playgrab the seeds from pit on your side of the board and place one in each subsequent pitgoing counterclockwise and skipping your opponent' store if your last seed lands in an empty pit of yoursmove the opposite pit' seeds into that pit if the last placed seed is in your storeyou get free turn |
6,892 | claims the remaining seeds for their storeand the winner is the one with the most seeds more information about mancala and its variants can be found at the program in action when you run mancala pythe output will look like thismancalaby al sweigart al@inventwithpython com --snip-+++--<<<<<-player ----+++ | | | | | | ++++++ | | | | | | ++++-player ->>++player choose movea- (or quitf +++--<<<<<-player ----+++ | | | | | | ++++++ | | | | | | ++++-player ->>++player choose moveg- (or quit--snip-how it works mancala uses ascii art to display the board notice that each pocket needs to have not only the number of seeds in it but label as well to avoid confusionthe labels use the letters through so they won' be mistaken for the number of seeds in each pocket the dictionaries next_pit and opposite_pit map the letter of one pocket to the letter of the pit next to or opposite itrespectively this lets the expression next_pit[' 'evaluate to 'band the expression opposite_pit[' 'evaluate to 'gpay attention to how the code uses these dictionaries without themour mancala program would require long series of if and elif statements to carry out the same game steps mancala |
6,893 | the ancient seed-sowing game view this code at tagslargeboard gamegametwo-player"" import sys tuple of the player' pits player_ _pits (' '' '' '' '' '' ' player_ _pits (' '' '' '' '' '' ' dictionary whose keys are pits and values are opposite pit opposite_pit {' '' '' '' '' '' '' '' '' '' ' ' '' '' '' '' '' '' '' '' '' ' ' '' '' '' ' dictionary whose keys are pits and values are the next pit in order next_pit {' '' '' '' '' '' '' '' '' '' '' '' ' ' '' '' '' '' '' '' '' '' '' '' '' ' ' '' '' '' ' every pit labelin counterclockwise order starting with pit_labels 'abcdef lkjihg how many seeds are in each pit at the start of new game starting_number_of_seeds (!try changing this to or def main() print('''mancalaby al sweigart al@inventwithpython com the ancient two-player seed-sowing game grab the seeds from pit on your side and place one in each following pitgoing counterclockwise and skipping your opponent' store if your last seed lands in an empty pit of yoursmove the opposite pit' seeds into that pit the goal is to get the most seeds in your store on the side of the board if the last placed seed is in your storeyou get free turn the game ends when all of one player' pits are empty the other player claims the remaining seeds for their storeand the winner is the one with the most seeds more info at ''' input('press enter to begin ' gameboard getnewboard( playerturn ' player goes first while truerun player' turn "clearthe screen by printing many newlinesso the old board isn' visible anymore print('\ display board and get the player' move project # |
6,894 | displayboard(gameboard playermove askforplayermove(playerturngameboard carry out the player' move playerturn makemove(gameboardplayerturnplayermove check if the game ended and player has won winner checkforwinner(gameboard if winner =' or winner =' ' displayboard(gameboarddisplay the board one last time print('player winner has won!' sys exit( elif winner ='tie' displayboard(gameboarddisplay the board one last time print('there is tie!' sys exit( def getnewboard() """return dictionary representing mancala board in the starting state seeds in each pit and in the stores "" syntactic sugar use shorter variable name starting_number_of_seeds create the data structure for the boardwith seeds in the stores and the starting number of seeds in the pits return {' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' def displayboard(board) """displays the game board as ascii-art based on the board dictionary "" seedamounts [ this 'ghijkl abcdefstring is the order of the pits left to right and top to bottom for pit in 'ghijkl abcdef' numseedsinthispit str(board[pit]rjust( seedamounts append(numseedsinthispit print("" +++--<<<<<-player ----+++ | | | | | | {{{{{{ {++++++{ | | | | | | {{{{{{ ++++-player ->>++ ""format(*seedamounts) mancala |
6,895 | def askforplayermove(playerturnboard) """asks the player which pit on their side of the board they select to sow seeds from returns the uppercase letter label of the selected pit as string "" while truekeep asking the player until they enter valid move ask the player to select pit on their side if playerturn =' ' print('player choose movea- (or quit)' elif playerturn =' ' print('player choose moveg- (or quit)' response input(''upper(strip( check if the player wants to quit if response ='quit' print('thanks for playing!' sys exit( make sure it is valid pit to select if (playerturn =' and response not in player_ _pitsor playerturn =' and response not in player_ _pits ) print('please pick letter on your side of the board ' continue ask player again for their move if board get(response= print('please pick non-empty pit ' continue ask player again for their move return response def makemove(boardplayerturnpit) """modify the board data structure so that the player or in turn selected pit as their pit to sow seeds from returns either ' or ' for whose turn it is next "" seedstosow board[pitget number of seeds from selected pit board[pit empty out the selected pit while seedstosow continue sowing until we have no more seeds pit next_pit[pitmove on to the next pit if (playerturn =' and pit =' 'or playerturn =' and pit =' ) continue skip opponent' store board[pit+ seedstosow - if the last seed went into the player' storethey go again if (pit =playerturn =' 'or (pit =playerturn =' ') the last seed landed in the player' storetake another turn return playerturn check if last seed was in an empty pittake opposite pit' seeds if playerturn =' and pit in player_ _pits and board[pit= project # |
6,896 | oppositepit opposite_pit[pit board[' '+board[oppositepit board[oppositepit elif playerturn =' and pit in player_ _pits and board[pit= oppositepit opposite_pit[pit board[' '+board[oppositepit board[oppositepit return the other player as the next player if playerturn =' ' return ' elif playerturn =' ' return ' def checkforwinner(board) """looks at board and returns either ' or ' if there is winner or 'tieor 'no winnerif there isn' the game ends when player' pits are all emptythe other player claims the remaining seeds for their store the winner is whoever has the most seeds "" player total board[' 'board[' 'board[' ' player total +board[' 'board[' 'board[' ' player total board[' 'board[' 'board[' ' player total +board[' 'board[' 'board[' ' if player total = player gets all the remaining seeds on their side board[' '+player total for pit in player_ _pits board[pit set all pits to elif player total = player gets all the remaining seeds on their side board[' '+player total for pit in player_ _pits board[pit set all pits to else return 'no winnerno one has won yet game is overfind player with largest score if board[' 'board[' '] return ' elif board[' 'board[' '] return ' else return 'tie if the program is run (instead of imported)run the game if __name__ ='__main__' main(mancala |
6,897 | experimental changes to it on your ownyou can also try to figure out how to do the followingchange the board to have more pits randomly select bonus pit thatwhen the last seed lands in itlets the player take another turn create square-shaped board for four players instead of two exploring the program try to find the answers to the following questions experiment with some modifications to the code and rerun the program to see what effect the changes have what happens if you change return ' on line to return ' ' what happens if you change return ' on line to return ' ' what happens if you change response ='quiton line to response ='quit' what happens if you change board[pit on line to board[pit what happens if you change print('\ on line to print('\ ) what happens if you change playerturn ' on line to playerturn ' ' what happens if you change board get(response= on line to board get(response=- project # |
6,898 | ma ze runner this two-dimensional maze runner shows the player top-downbird' -eye view of maze file you create in text editorsuch as the ide you use to write your py files using the wasd keysthe player can move upleftdownand rightrespectivelyto navigate the symbol toward the exit marked by the character to make maze fileopen text editor and create the following pattern don' type the numbers along the top and left sidethey are only there for reference ######## # ######## ######## |
6,899 | ######## # ########the characters represent wallsthe marks the startand the marks the exit the characters in bold represent walls that you can remove to form your maze don' remove the walls at odd-numbered columns and odd-numbered rowsand don' remove the borders of the maze when you're donesave the maze as txt (textfile it could look something like this######### ######### ########of coursethis is simple maze you can make maze files of any size as long as they have an odd number of rows and columns be sure it'll still fit on the screenthoughyou can also download maze files from invpy com/mazesthe program in action when you run mazerunner pythe output will look like thismaze runner dby al sweigart al@inventwithpython com (maze files are generated by mazemakerrec pyenter the filename of the maze (or list or quit)maze txt #################################################################@############################################################################################################################################## ################################################################ enter directionor quitasd --snip- project # |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.