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... |
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 insteadconside... |
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 inhab... |
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 fram... |
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 ne... |
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 [ f... |
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'r... |
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 fro... |
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[... |
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 presseden... |
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 shape... |
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 colorblindnessca... |
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... |
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(' ') display... |
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 ea... |
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 retu... |
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 following... |
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 m... |
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 ... |
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 ... |
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 str... |
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 ... |
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 si... |
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_h... |
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 displayboa... |
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 spacesoth... |
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... |
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 i... |
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 numbe... |
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 ... |
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 ... |
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 give... |
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?... |
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 ... |
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... |
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 (lef... |
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 foll... |
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 yo... |
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... |
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 mak... |
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 mu... |
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 ... |
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... |
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 ... |
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 hundredsthous... |
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 cha... |
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 mov... |
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... |
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 simu... |
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 itfallingdir... |
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 progr... |
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 persona... |
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 x... |
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_r... |
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(wi... |
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... |
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 th... |
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)ru... |
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 locati... |
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 ... |
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''a... |
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[interv... |
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 (wro... |
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(... |
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[curren... |
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 knownsus... |
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 th... |
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... |
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 d... |
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 a... |
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'=e... |
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[... |
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... |
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 o... |
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']' '[']-[''|-|']' '[' ''!''|']' '[']<'] ' '[' ... |
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... |
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 ... |
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 luckg... |
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 ... |
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 ... |
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]> ) sinc... |
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 ente... |
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 bet... |
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 th... |
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 y... |
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... |
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 ----+++ | | | | | | ++... |
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 {' '' '' '' '' '' '' '' '' '' ' ' '' '' '' '' '' '' '' '' ''... |
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 w... |
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... |
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 checkf... |
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 an... |
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 fi... |
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 (textfil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.