id
int64
0
25.6k
text
stringlengths
0
4.59k
6,900
the program loads the data for the maze' walls from text file and into dictionary stored in the maze variable this dictionary has (xytuples for keys and the string in the wallemptystartor exit constants for values project "maze runner ,uses similar dictionary representation of the maze the difference between the projec...
6,901
if filename upper(='list' print('maze files found in'os getcwd() for fileincurrentfolder in os listdir() if (fileincurrentfolder startswith('maze'and fileincurrentfolder endswith(txt')) print('fileincurrentfolder continue if filename upper(='quit' sys exit( if os path exists(filename) break print('there is no file name...
6,902
if move not in [' '' '' '' ']print('invalid direction enter one of wasor 'continue check if the player can move in that directionif move ='wand maze[(playerxplayery )=emptybreak elif move ='sand maze[(playerxplayery )=emptybreak elif move ='aand maze[(playerx playery)=emptybreak elif move ='dand maze[(playerx playery)=...
6,903
or maze[(playerxplayery )=empty)break break if we've reached branch point if (playerxplayery=(exitxexity)displaymaze(mazeprint('you have reached the exitgood job!'print('thanks for playing!'sys exit(exploring the program try to find the answers to the following questions experiment with some modifications to the code a...
6,904
ma ze runner this three-dimensional maze runner provides the player with first-person view from inside maze try to find your way outyou can generate maze files by following the instructions in project "maze runner ,or by downloading maze files from
6,905
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 ###############\|###############location ( directionnorth (wenter direction( (dor quit ###############\|#######...
6,906
____ |/||||__ __|||/|| |||\||| \ |||___|\|___ \ \ ____ /||__ __||/| ||\|| \ ||\|___ the periods in the ascii art in the source code get removed before the strings are displayedthey only exist to make entering the code easierso you don' insert or leave out blank spaces here is the source code for the maze """maze dby al...
6,907
walldict['width'width return walldict exit_dict {( )' '( )' '( )' ' ( )' ''height' 'width' the way we create the strings to display is by converting the pictures in these multiline strings to dictionaries using wallstrtowalldict( then we compose the wall for the player' location and direction by "pastingthe wall dictio...
6,908
''strip()paste to closed[' 'wallstrtowalldict( '' ''strip()paste to closed[' 'wallstrtowalldict( '' \ ''strip()paste to closed[' 'wallstrtowalldict( '' ''strip()paste to def displaywalldict(walldict) """display wall dictionaryas returned by wallstrtowalldict()on the screen "" print(block (walldict['width' ) for in rang...
6,909
def pastewalldict(srcwalldictdstwalldictlefttop) """copy the wall representation dictionary in srcwalldict on top of the one in dstwalldictoffset to the position given by lefttop "" dstwalldict copy copy(dstwalldict for in range(srcwalldict['width']) for in range(srcwalldict['height']) dstwalldict[( lefty top)srcwalldi...
6,910
for sec in 'abdcef' if section[sec=wall walldict pastewalldict(closed[sec]walldict paste_closed_to[sec][ ]paste_closed_to[sec][ ] draw the exit sign if needed if section[' '=exit walldict pastewalldict(exit_dictwalldict if section[' '=exit walldict pastewalldict(exit_dictwalldict if section[' '=exit walldict pastewalld...
6,911
maze[(xy)character elif character =start pxpy xy maze[(xy)empty elif character =exit exitxexity xy maze[(xy)empty + height assert px !none and py !none'no start point in file assert exitx !none and exity !none'no exit point in file pdir north while truemain game loop displaywalldict(makewalldict(mazepxpypdirexitxexity)...
6,912
elif move startswith(' ')cheat code' ,ypxpy move split()[ split(','px int(pxpy int(pybreak elseprint('you cannot move in that direction 'if (pxpy=(exitxexity)print('you have reached the exitgood job!'print('thanks for playing!'sys exit(exploring the program try to find the answers to the following questions experiment ...
6,913
million dice roll tat at when you roll two six-sided dicethere' percent chance you'll roll that' much better than the odds of rolling just percent that' because there' only one combination of dice rolls that gives you (the one that occurs when both dice roll )but many combinations add up to seven and and and and so on ...
6,914
when you run milliondicestats pythe output will look like thismillion dice roll statistics simulator by al sweigart al@inventwithpython com enter how many six-sided dice you want to roll simulating , , rolls of dice done done total rolls percentage rolls rolls rolls rolls rolls rolls rolls rolls rolls rolls rolls how i...
6,915
numberofdice int(input('') set up dictionary to store the results of each dice roll results { for in range(numberofdice(numberofdice ) results[ simulate dice rolls print('simulating , , rolls of {dice format(numberofdice) lastprinttime time time( for in range( ) if time time(lastprinttime print('{}done format(round( ))...
6,916
at piet mondrian was th-century dutch painter and one of the founders of neoplasticisman abstract art movement his most iconic paintings relied on blocks of primary colors (blueyellowred)blackand white using minimalist approachhe separated these colors with horizontal and vertical elements this program generates random...
6,917
generated each time the program runs how it works the algorithm works by creating data structure (the canvas dictionarywith randomly spaced vertical and horizontal linesas in figure - figure - the first step of the mondrian art algorithm creates grid project #
6,918
as shown in figure - figure - the second step of the mondrian art algorithm removes some lines at random finallythe algorithm randomly fills some rectangles with yellowredblueor blackas in figure - figure - the third step of the mondrian art algorithm randomly selects rectangles to fill with color mondrian art generato...
6,919
sample images """mondrian art generatorby al sweigart al@inventwithpython com randomly generates art in the style of piet mondrian more info at view this code at tagslargeartisticbext"" import sysrandom try import bext except importerror print('this program requires the bext modulewhich you' print('can install by follo...
6,920
generate horizontal linesy random randint(min_y_increasemax_y_increasewhile height min_y_increasenumberofsegmentstodelete + for in range(width)canvas[(xy)black +random randint(min_y_increasemax_y_increasenumberofrectanglestopaint numberofsegmentstodelete numberofsegmentstodelete int(numberofsegmentstodelete randomly se...
6,921
project # elsepointstodelete append((startxy)elif orientation ='horizontal'go up one path from the start pointand see if we can remove this segmentfor changex in (- ) startx while width +changex if (canvas[(xstarty )=black and canvas[(xstarty )=black)we've found four-way intersection break elif ((canvas[(xstarty )=whit...
6,922
xy pointstopaint pop(canvas[(xy)colortopaint if canvas[( )=whitepointstopaint add(( )if canvas[( )=whitepointstopaint add(( )if canvas[(xy )=whitepointstopaint add((xy )if canvas[(xy )=whitepointstopaint add((xy )draw the canvas data structurefor in range(height)for in range(width)bext bg(canvas[(xy)]print('end=''print...
6,923
mont hall problem the monty hall problem illustrates surprising fact of probability the problem is loosely based on the old game show let' make deal and its hostmonty hall in the monty hall problemyou can pick one of three doors behind one door is prizea new car each of the other two doors opens onto worthless goat say...
6,924
you correctly picked the car door to begin with ( in , chance)then the host left random goat door closed if you picked goat door ( in , chance)the host specifically chose the car door to leave closed the choice of which doors to open isn' randomthe host knows to leave the car door closed it' almost certain that you did...
6,925
you wonswapping wins lossessuccess rate not swapping wins lossessuccess rate press enter to repeat the experiment --snip-how it works the multiline strings for the ascii-art doors are stored in several constant variablessuch as all_closedfirst_goatand first_car_others_goat the code that uses these constantslike print(f...
6,926
+++ ( oo / /| |goat|| ++++"" first_car_others_goat "" +++ car(( __oo oo / /| / /| / __ |goat|||goat|| ++++"" second_car_others_goat "" +++ (car( oo __oo / /|__/ /| / __ |goat|| |goat|| ++++"" third_car_others_goat "" +++ ((car oo oo __ / /| / /|__ / __ |goat|||goat|| ++++"" print('''the monty hall problemby al sweigart...
6,927
swapwins swaplosses staywins staylosses while truemain program loop the computer picks which door has the car doorthathascar random randint( ask the player to pick door print(all_closed while truekeep asking the player until they enter valid door print('pick door or (or "quitto stop):' response input(''upper( if respon...
6,928
elif doorpick = and showgoatdoor = doorpick elif doorpick = and showgoatdoor = doorpick elif doorpick = and showgoatdoor = doorpick elif doorpick = and showgoatdoor = doorpick open all the doorsif doorthathascar = print(first_car_others_goatelif doorthathascar = print(second_car_others_goatelif doorthathascar = print(t...
6,929
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 doorthathascar random randint( on line to doorthathascar what happens if you replace lines to with print([first_goatsecond_goatthird_goat...
6,930
lt at ta this program generates multiplication table from to while simpleit provides useful demonstration of nested loops
6,931
when you run multiplicationtable pythe output will look like thismultiplication tableby al sweigart al@inventwithpython com --+ how it works line prints the top row of the table notice that it sets large enough distance between the numbers to accommodate products that are maximum of three digits long since this is mult...
6,932
for number in range( )print the product followed by spaceprint(str(number number rjust( )end='print(finish the row by printing newline 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 ha...
6,933
yn "ninety-nine bottlesis folk song of undetermined origin known for its length and repetitiveness the lyrics go"ninetynine bottles of milk on the wallninety-nine bottles of milk take one downpass it aroundninetyeight bottles of milk on the wall as the lyrics repeatthe number of bottles falls from ninety-eight to ninet...
6,934
when you run ninetyninebottles pythe output will look like thisninety-nine bottlesby al sweigart al@inventwithpython com (press ctrl- to quit bottles of milk on the wall bottles of milktake one downpass it around bottles of milk on the wall bottles of milk on the wall bottles of milktake one downpass it around bottles ...
6,935
bottles bottles decrease the number of bottles by one print(bottles'bottles of milk on the wall!' time sleep(pause print(print newline display the last stanza print(' bottle of milk on the wall,' time sleep(pause print(' bottle of milk,' time sleep(pause print('take it downpass it around,' time sleep(pause print('no mo...
6,936
yn in this version of the song "ninety-nine bottles,the program introduces small imperfections in each stanza by either removing letterswapping the casing of lettertransposing two lettersor doubling letter as the song continues to playthese mutations add upresulting in very silly song it' good idea to try project "nine...
6,937
when you run ninetyninebottles pythe output will look like thisninety-nniine boottelsby al sweigart al@inventwithpython com --snip- bottles of milk on the wall bottles of milktake one downpass it around bottles of milk on the wall bottles of milk on the wall bottles of milktake one wnpass it around bottles of milk on t...
6,938
set up the constants (!try changing both of these to to print all the lyrics at once speed the pause in between printing letters line_pause the pause at the end of each line def slowprint(textpauseamount= ) """slowly print out the characters in text one at time "" for character in text set flush=true here so the text i...
6,939
effect random randint( if effect = replace character with space charindex random randint( len(line line[charindex elif effect = change the casing of character charindex random randint( len(line if line[charindexisupper() line[charindexline[charindexlower( elif line[charindexislower() line[charindexline[charindexupper( ...
6,940
numer al system counters we're used to counting in the decimal numeral systemwhich uses digits through this system likely developed because humans counted on their fingersand most people have fingers but other number systems exist computers make use of binarya numeral system with only two digits and programmers also so...
6,941
when you run numeralsystems pythe output will look like thisnumeral system countersby al sweigart al@inventwithpython com --snip-enter the starting number ( enter how many numbers to display ( dec hex bin dec hex bin dec hex bin dec hex bin dec hex bin dec hex bin dec hex bin dec hex bin dec hex bin dec hex bin dec hex...
6,942
decimalwith the decimal number "ten thousand the numeral systems program removes these prefixes before displaying the number """numeral system countersby al sweigart al@inventwithpython com shows equivalent numbers in decimalhexadecimaland binary view this code at tagstinymath"" print('''numeral system countersby al sw...
6,943
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 hex(number)[ :upper(on line to hex(number)[ :] what error do you cause if you change int(responseon line to response project #
6,944
ta the elements the periodic table of the elements organizes all known chemical elements into single table this program presents this table and lets the player access additional information about each elementsuch as its atomic numbersymbolmelting pointand so on compiled this information from wikipedia and stored it in ...
6,945
when you run periodictable pythe output will look like thisperiodic table of elements by al sweigart al@inventwithpython com periodic table of elements he li be ne na mg al si cl ar ca sc ti cr mn fe co ni cu zn ga ge as se br kr rb sr zr nb mo tc ru rh pd ag cd in sn sb te xe cs ba la hf ta re os ir pt au hg tl pb bi ...
6,946
displays atomic information for all the elements view this code at tagsshortscience"" data from highlight the tablecopy itthen paste it into spreadsheet program like excel or google sheets like in then save this file as periodictable csv or download this csv file from import csvsysre read in all the data from periodict...
6,947
element[keyre sub( '\[( | | )+\]'''value elements[line[ ]element map the atomic number to the element elements[line[ ]element map the symbol to the element print('periodic table of elements' print('by al sweigart al@inventwithpython com' print( while truemain program loop show table and let the user select an element p...
6,948
at pig latin is word game that transforms english words into parody of latin in pig latinif word begins with consonantthe speaker removes this letter and puts it at the endfollowed by "ay for example"pigbecomes "igpayand "latinbecomes "atinlay otherwiseif the word begins with vowelthe speaker simply adds "yayto the end...
6,949
when you run piglatin pythe output will look like thisigpay atinlay (pig latinby al sweigart al@inventwithpython com enter your messagethis is very serious message isthay isyay ayay eryvay erioussay essagemay (copied pig latin to clipboard how it works the englishtopiglatin(function takes string of english text and ret...
6,950
def englishtopiglatin(message) piglatin ' string of the pig latin translation for word in message split() separate the non-letters at the start of this word prefixnonletters ' while len(word and not word[ isalpha() prefixnonletters +word[ word word[ : if len(word= piglatin piglatin prefixnonletters continue separate th...
6,951
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 message split(on line to message what happens if you change (' '' '' '' '' '' 'on line to () what happens if you change (' '' '' '' '' ''...
6,952
pow erball lot tery the powerball lottery is an exciting way to lose small amounts of money if you purchase $ ticketyou can pick six numbersfive drawn from to and sixth "powerballnumber drawn from to the order of the numbers doesn' matter if the lottery selects your six numbersyou win $ billion dollarsexcept you won' w...
6,953
the next time you want to buy lottery ticketpick the numbers and those numbers are just as likely to come up as more complex set the program in action when you run powerballlottery pythe output will look like thispowerball lotteryby al sweigart al@inventwithpython com each powerball lottery ticket costs $ the jackpot f...
6,954
print('''powerball lotteryby al sweigart al@inventwithpython com each powerball lottery ticket costs $ the jackpot for this game is $ billionit doesn' matter what the jackpot isthough because the odds are in , , so you won' win this simulation gives you the thrill of playing without wasting money ''' let the player ent...
6,955
continue check that the number is between and if not ( <powerball < ) print('the powerball number must be between and ' continue break enter the number of times you want to play while true print('how many times do you want to play(max )' response input('' convert the strings into integers try numplays int(response exce...
6,956
print('you would be billionaire if this was real!' break else print(you lost 'the leading space is required here print('you have wasted'price print('thanks for playing!'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 wh...
6,957
prime numbers prime number is number that is evenly divisible only by one and itself prime numbers have variety of practical applicationsbut no algorithm can predict themwe must calculate them one at time howeverwe do know that there is an infinite number of prime numbers to be discovered this program finds prime numbe...
6,958
when you run primenumbers pythe output will look like thisprime numbersby al sweigart al@inventwithpython com --snip-enter number to start searching for primes from(try or ( zerosor another number press ctrl- at any time to quit press enter to begin --snip-how it works the isprime(function accepts an integer and return...
6,959
response input('' if response isdecimal() num int(response break input('press ctrl- at any time to quit press enter to begin ' while true print out any prime numbers if isprime(num) print(str(num''end=''flush=true num num go to the next number def isprime(number) """returns true if number is primeotherwise returns fals...
6,960
progress bar progress bar is visual element that shows how much of task has been completed progress bars are often used alongside downloading files or software installations this project creates getprogressbar(function that returns progress bar string based on the arguments passed to it it simulates downloading filebut...
6,961
when you run progressbar pythe output will look like thisprogress bar simulationby al sweigart [######## / how it works the progress bar relies on certain trick that programs running in terminal windows can perform just as '\nand '\tare escape characters for newline and tab charactersrespectively'\bis an escape charact...
6,962
time sleep( pause for little bit print backspaces to move the text cursor to the line' start print('\blen(barstr)end=''flush=true def getprogressbar(progresstotalbarwidth= ) """returns string that represents progress bar that has barwidth bars and has progressed progress amount out of total amount "" progressbar 'the p...
6,963
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 print('\blen(barstr)end=''flush=trueon line what happens if you switch the order of lines and what happens if you change r...
6,964
ainbow rainbow is simple program that shows colorful rainbow traveling back and forth across the screen the program makes use of the fact that when new lines of text appearthe existing text scrolls upcausing it to look like it' moving this program is good for beginnersand it' similar to project "deep cave
6,965
figure - shows what the output will look like when you run rainbow py figure - the zigzag output of the rainbowwhich is in color on the screen how it works this program continuously prints the same rainbow pattern what changes is the number of space characters printed to the left of it increasing this number moves the ...
6,966
print('rainbowby al sweigart al@inventwithpython com' print('press ctrl- to stop ' time sleep( indent how many spaces to indent indentincreasing true whether the indentation is increasing or not try while truemain program loop print(indentend='' bext fg('red' print('##'end='' bext fg('yellow' print('##'end='' bext fg('...
6,967
ro pa sc so in this version of the two-player hand game also known as rochambeau or jan-ken-ponthe player faces off against the computer you can pick either rockpaperor scissors rock beats scissorsscissors beats paperand paper beats rock this program adds some brief pauses for suspense for variation of this gamesee pro...
6,968
when you run rockpaperscissors pythe output will look like thisrockpaperscissorsby al sweigart al@inventwithpython com rock beats scissors paper beats rocks scissors beats paper wins losses ties enter your move( )ock ( )aper ( )cissors or ( )uit rock versus scissors you win wins losses ties enter your move( )ock ( )ape...
6,969
project # print('enter your move( )ock ( )aper ( )cissors or ( )uit'playermove input(''upper(if playermove =' 'print('thanks for playing!'sys exit(if playermove ='ror playermove ='por playermove =' 'break elseprint('type one of rpsor 'display what the player choseif playermove =' 'print('rock versus 'playermove 'rockel...
6,970
elif playermove ='rockand computermove ='paper'print('you lose!'losses losses elif playermove ='paperand computermove ='scissors'print('you lose!'losses losses elif playermove ='scissorsand computermove ='rock'print('you lose!'losses losses after entering the source code and running it few timestry making experimental ...
6,971
ro pa sc so ay this variant of rock paper scissors is identical to project "rock paper scissors,except the player will always win the code selecting the computer' move is set so that it always chooses the losing move you can offer this game to your friendswho may be excited when they win at first see how long it takes ...
6,972
when you run rockpaperscissorsalwayswin pythe output will look like thisrockpaperscissorsby al sweigart al@inventwithpython com rock beats scissors paper beats rocks scissors beats paper wins losses ties enter your move( )ock ( )aper ( )cissors or ( )uit paper versus rock you win wins losses ties enter your move( )ock ...
6,973
print('''rockpaperscissorsby al sweigart al@inventwithpython com rock beats scissors paper beats rocks scissors beats paper ''' these variables keep track of the number of wins wins while truemain game loop while truekeep asking until player enters rpsor print('{wins losses tiesformat(wins) print('enter your move( )ock...
6,974
experimental changes to it on your ownyou can also try to figure out how to do the followingadd "lizardand "spockmoves to the game lizard poisons spock and eats paperbut is crushed by rock and decapitated by scissors spock breaks scissors and vaporizes rockbut is poisoned by lizard and disproved by paper allow the play...
6,975
rot cipher the rot cipherone of the simplest encryption algorithmsstands for "rotate spaces the cypher represents the letters to as the numbers to in such way that the encrypted letter is spaces from the plaintext lettera becomes nb becomes oand so on the encryption process is identical to the decryption processmaking ...
6,976
when you run rot cipher pythe output will look like thisrot cipherby al sweigart al@inventwithpython com enter message to encrypt/decrypt (or quit)meet me by the rose bushes tonight the translated message iszrrg zr ol gur ebfr ohfurf gbavtug (copied to clipboard enter message to encrypt/decrypt (or quit)--snip-how it w...
6,977
translated 'for character in messageif character isupper()concatenate uppercase translated character transcharindex (upper_letters find(character translated +upper_letters[transcharindexelif character islower()concatenate lowercase translated character transcharindex (lower_letters find(character translated +lower_lett...
6,978
tat this project features an animation of cube rotating using trigonometric functions you can adapt the point rotation math and the line(function in your own animation programs although the block text characters we'll use to draw the cube don' look like thinstraight linesthis kind of drawing is called wireframe model b...
6,979
the program in action figure - shows what the output will look like when you run rotatingcube py figure - the wireframe cube that the program draws to the screen project #
6,980
this algorithm has two main partsthe line(function and the rotatepoint(function the cube has eight pointsone for each corner the program stores these corners as (xyztuples in the cube_corners list these points also define the connections for the cube' edge lines when all the points rotate in the same direction by the s...
6,981
project # check for the special case where the start and end points are certain neighborswhich this function doesn' handle correctlyand return hard coded list insteadif ( = and = or ( = and = )return [( )( )issteep abs( abs( if issteepthis algorithm only handles non-steep linesso let' change the slope to non-steep and ...
6,982
return points def rotatepoint(xyzaxayaz) """returns an (xyztuple of the xyz arguments rotated the rotation happens around the origin by angles axayaz (in radians directions of each axis - +-+ + "" rotate around axis rotatedx rotatedy ( math cos(ax)( math sin(ax) rotatedz ( math sin(ax)( math cos(ax) xyz rotatedxrotated...
6,983
- ]point [- - ]point - ]point [- ]point ]point rotatedcorners stores the xyz coordinates from cube_corners after they've been rotated by rxryand rz amounts rotatedcorners [nonenonenonenonenonenonenonenone rotation amounts for each axis xrotation yrotation zrotation try while truemain program loop rotate the cube along ...
6,984
os system('cls'windows uses the cls command else os system('clear'macos and linux use the clear command except keyboardinterrupt print('rotating cubeby 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 change...
6,985
ya the royal game of ur is , -year-old game from mesopotamia archeologists rediscovered the game in the royal cemetery at urin modern-day southern iraqduring excavations between and the rules were reconstructed from the game board (shown in figure - and babylonian clay tabletand they're similar to parcheesi you'll need...
6,986
two players each begin with seven tokens in their homeand the first player to move all seven to the goal is the winner players take turns throwing four dice these dice are four-pointed pyramid shapes called tetrahedrons each die has two marked pointsgiving an even chance that the dice come up marked or unmarked instead...
6,987
when you run royalgameofur pythe output will look like thisthe royal game of urby al sweigart --snip-xxxxxxx home goal ++++-- --+--^--+|*****|*****|*|*|****hgfe|****ts+-- --+++++++--^--|*****>*ijk|****lmnop+--^--+++++++-- --|*****|*****|*|*|****dcba|****rq++++--^--+-- --+ home goal ooooooo it is ' turn press enter to f...
6,988
"" import randomsys x_player ' o_player ' empty set up constants for the space labels x_home 'x_home o_home 'o_home x_goal 'x_goal o_goal 'o_goal the spaces in left to righttop to bottom order all_spaces 'hgfetsijklmnopdcbarq x_track 'hefghijklmnopstg( stands for homeg stands for goal o_track 'habcdijklmnopqrg flower_s...
6,989
home goal +---+---+---+- -+-^-+--- | <<<<<<<<<<<<^<|< | + --+---+---+---+---+---+---+-^- |>> |>> +^--+---+---+---+---+---+---+- - | |^<<<<<<<<<<<< <<< +---+---+---+-^-+- -+--- home goal if you land on an opponent' token in the middle trackit gets sent back home the **flower*spaces let you take another turn tokens in th...
6,990
if fliptally = input('you lose turn press enter to continue 'turn opponent swap turns to the other player continue ask the player for their movevalidmoves getvalidmoves(gameboardturnfliptallyif validmoves =[]print('there are no possible movesso you lose turn 'input('press enter to continue 'turn opponent swap turns to ...
6,991
if nextboardspace in flower_spaces print(turn'landed on flower space and goes again ' input('press enter to continue ' else turn opponent swap turns to the other player def getnewboard() "" returns dictionary that represents the state of the board the keys are strings of the space labelsthe values are x_player o_player...
6,992
check if the player can move token from home if board[home and board[track[fliptally]=empty validmoves append('home' check which spaces have token the player can move for trackspaceindexspace in enumerate(track) if space ='hor space ='gor board[space!player continue nexttrackspaceindex trackspaceindex fliptally if next...
6,993
ay module seven-segment display is type of lcd component used to display numbers in pocket calculatorsmicrowave ovensand other small electronic devices through different combinations of seven line-shaped segments in an lcda seven-segment display can represent the digits through they look like this__ |____ __|__ __ ____...
6,994
even though it' modulesevseg py outputs sample demo of the digits it produces when you run the program directly the output will look like thisthis module is meant to be imported rather than run for examplethis codeimport sevseg mynumber sevseg getsevsegstr( print(mynumberwill print zero-padded to three digits__ __ |___...
6,995
project # rows[ +rows[ +continue skip the space in between digits elif numeral ='-'render the negative signrows[ +rows[ +__ rows[ +elif numeral =' 'render the rows[ +__ rows[ +'|rows[ +'|__|elif numeral =' 'render the rows[ +rows[ +|rows[ +|elif numeral =' 'render the rows[ +__ rows[ +__|rows[ +'|__ elif numeral =' 're...
6,996
return '\njoin(rows if this program isn' being importeddisplay the numbers to if __name__ ='__main__' print('this module is meant to be imported rather than run ' print('for examplethis code:' print(import sevseg' print(mynumber sevseg getsevsegstr( )' print(print(mynumber)' print( print(will print zero-padded to three...
6,997
shining carpet the shininga psychological horror film directed by stanley kubricktakes place at the haunted overlook hotel the hotel carpet' hexagonal design became an iconic part of this famous movie the carpet features alternating and interlocking hexagons whose mesmerizing effect is well-suited for such an unnerving...
6,998
when you run shiningcarpet pythe output will look like this_ \____ \____ \____ \____ \____ \___ \____ \____ \____ \____ \____ \____ \\\\\\___ \____ \____ \____ \____ \____ \ __ \____ \____ \____ \____ \____ \__ __\\\\\\___ \____ \____ \____ \____ \____ \___ \____ \____ \____ \____ \____ \____ \\\\\\___ \____ \____ \___...
6,999
y_repeat how many times to tessellate vertically for in range(y_repeat) print( ' \___x_repeat print( \____x_repeat print( '\x_repeat print( '___ \_x_repeat print( '__ \__x_repeat print( '__\___x_repeatexploring the program for practicetry creating patterns such as the following___|___|___|___|___|___|___|___|___|___|__...