id
int64
0
25.6k
text
stringlengths
0
4.59k
7,600
if not playagain()break lines and are located immediately after the while-block started by the while statement on line gameisplaying is set to false when the game has endedso at this point the game asks the player if they want to play again if playagain(returns falsethen the if statement' condition is true (because the...
7,601
bagels topics covered in this augmented assignment operators+=-=*=/the random shuffle(function the sort(and join(list methods string interpolation (also called string formattingconversion specifier % nested loops in this you'll learn few new methods and functions that come with python you'll also learn about augmented ...
7,602
fermi guess # pico guess # fermi guess # bagels guess # bagels guess # fermi fermi guess # fermi pico guess # you got itdo you want to play again(yes or nono source code of bagels if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at bagels py import random...
7,603
return 'you got it! clue [ for in range(len(guess)) if guess[ =secretnum[ ] clue append('fermi' elif guess[iin secretnum clue append('pico' if len(clue= return 'bagels clue sort( return join(clue def isonlydigits(num) returns true if num is string made up only of digits otherwise returns false if num ='' return false f...
7,604
print(' have thought up number you have % guesses to get it (maxguess) numguesses while numguesses <maxguess guess ' while len(guess!numdigits or not isonlydigits(guess) print('guess #% (numguesses) guess input( clue getclues(guesssecretnum print(clue numguesses + if guess =secretnum break if numguesses maxguess print(...
7,605
figure - flow chart for the bagels game shuffling unique set of digits numbers list(range( )random shuffle(numbersline ' list(range( )always evaluate to [ it' just easier to type list(range( )the numbers variable contains list of all ten digits the random shuffle(function the random shuffle(function randomly changes th...
7,606
[ random shuffle(spamprint(spam[ random shuffle(spamprint(spam[ random shuffle(spamprint(spam[ you want the secret number in bagels to have unique digits the bagels game is much more fun if you don' have duplicate digits in the secret numbersuch as ' or ' the shuffle(function will help you do this getting the secret nu...
7,607
augmented assignment operators the +operator on line is one of the augmented assignment operators normallyif you wanted to add or concatenate value to variableyou would use code that looked like thisspam spam spam eggs 'hello eggs eggs 'world!the augmented assignment operators are shortcut that frees you from retyping ...
7,608
clue [for in range(len(guess))if guess[ =secretnum[ ]clue append('fermi'elif guess[iin secretnumclue append('pico'if the guess isn' the same as the secret numberthe code must figure out what clues to give the player the list in clue will start empty and have 'fermiand 'picostrings added as needed do this by looping thr...
7,609
the sort(method doesn' return sorted listbut rather sorts the list it is called on "in placethis is just like how the reverse(method works you would never want to use this line of codereturn spam sort(because that would return the value none (which is what sort(returnsinstead you would want separate line spam sort(and ...
7,610
the isonlydigits(helps determine if the player entered valid guess line checks if num is the blank stringand if soreturns false for in numif not in ' split()return false return true the for loop iterates over each character in the string num the value of will have single character on each iteration inside the for-block...
7,611
after all of the function definitionsthis is the actual start of the program instead of using the integer in our program for the number of answer hasuse the constant variable numdigits the same goes for using the constant variable maxguess instead of the integer for the number of guesses the player gets now it will be ...
7,612
string interpolation can make your code much easier to type the first variable name is used for the first %sthe second variable with the second % and so on you must have the same number of % conversion specifiers as you have variables another benefit of using string interpolation instead of string concatenation is inte...
7,613
guess then line has new while loop that loops as long as numguesses is less than or equal to maxguess getting the player' guess guess 'while len(guess!numdigits or not isonlydigits(guess)print('guess #% (numguesses)guess input(the guess variable will hold the player' guess returned from input(the code keeps looping and...
7,614
if guess is the same value as secretnumthe player has correctly guessed the secret number and line breaks out of the while loop that was started on line if notthen execution continues to line where it checks if the player ran out of guesses if sothe program tells the player they've lost at this pointexecution jumps bac...
7,615
cartesian coordinates topics covered in this cartesian coordinate systems the -axis and -axis the commutative property of addition absolute values and the abs(function this doesn' introduce new game instead it goes over some simple mathematical concepts you will use in the rest of this book in games the graphics on the...
7,616
common way to refer to specific places on chessboard is by marking each row and column with letters and numbers figure - is chessboard that has each row and each column marked coordinate for space on the chessboard is combination of row and column in chessthe knight piece looks like horse head the white knight in figur...
7,617
subtract the black knight' -coordinate and white knight' -coordinate the black knight has to move along the -axis by four spaces subtract the black knight' -coordinate and white knight' -coordinate the black knight has to move along the -axis by two spaces by doing some math with the coordinate numbersyou can figure ou...
7,618
figure - moving the white knight to the left subtracts from the coordinate the white knight ends up at position - that means equals - if you add or subtract negative numberthe white knight would move in the opposite direction if you add negative numberthe knight moves to the left if you subtract negative numberthe knig...
7,619
you can think of the -axis as number line add another number line going up and down for the -axis if you put these two number lines togetheryou have cartesian coordinate system like in figure - adding positive number (or subtracting negative numberwould move the knight up the number lineand subtracting positive number ...
7,620
figure - trick subtracting positive and negative number trick the commutative property of addition you can always swap the numbers in addition this is the commutative property of addition that means that doing swap like to will not change the answer if you count the boxes in figure - you can see that it doesn' matter i...
7,621
figure - using the math tricks together absolute values and the abs(function the absolute value of number is the number without the negative sign in front of it thereforepositive numbers do not changebut negative numbers become positive for examplethe absolute value of - is the absolute value of - is the absolute value...
7,622
coordinate system of computer screen figure - the cartesian coordinate system on computer screen it is common that computer screens use coordinate system that has the origin ( at the top left corner of the screenwhich increases going down and to the right this is shown in figure there are no negative coordinates most c...
7,623
sonar treasure hunt topics covered in this data structures the remove(list method the isdigit(string method the sys exit(function the game in this is the first to make use of cartesian coordinates that you learned about in the game also has data structures (which is just fancy way of saying complex variables such as th...
7,624
figure - combining multiple square rings of shows where treasure chests could be but multiple sonar devices working together can narrow it to an exact place where the rings intersect each other see figure - (normally these rings would be circlesbut this game will use squares to make programming it easier sample run of ...
7,625
`~~~`~~~`~`~~`~~~~~`~``~~~~`~`~~~`~``~``~~````~`~```~`~~~~` ~`~~~```~~~~`~`~~`~``~`~~```~`~`~~`~`~~~~~~`~`````~`~~`~~~~ `~``~``~~~`~``~`~`~``~`````~~~~~~~~~`~`~~`~``~~~~~```~~`~`` ``~`~~``~`~``~`~`~`~~`~`~~`~`~``~~~`~``~````~``````~~~~``~` ``~~`~~~``~``~~````~`~`~`~``~~~``~~```~`~~`~~`~`~`~~`~~~~`` ~~```~~~`~`~~``~`~``...
7,626
`~~~`~~~`~`~~`~~~~~`~``~~~~`~`~~~`~``~``~~````~`~```~`~~~~` ~`~~~```~~~~`~`~~`~``~`~~```~`~`~~`~`~~~~~~`~`````~`~~`~~~~ `~``~``~~~`~``~`~`~``~`````~~~~~~~~~`~`~~`~``~~~~~```~~`~`` ``~`~~``~`~``~`~`~`~~`~`~~`~`~``~~~`~``~````~``````~~~~``~` ``~~`~~~``~``~~````~`~`~`~``~~~``~~```~`~~`~~`~`~`~~`~~~~`` ~~```~~~`~`~~``~`~``...
7,627
do you want to play again(yes or nono source code of sonar treasure hunt below is the source code for the game type it into new filethen save the file as sonar py and run it by pressing the key if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at sonar py ...
7,628
return string from the board data structure at certain row boardrow ' for in range( ) boardrow +board[ ][row return boardrow def getnewboard() create new board data structure board [ for in range( )the main list is list of lists board append([] for in range( )each list in the main list has singlecharacter strings use d...
7,629
distance abs(cy if distance smallestdistancewe want the closest treasure chest smallestdistance distance if smallestdistance = xy is directly on treasure chest chests remove([xy] return 'you have found sunken treasure chest! else if smallestdistance board[ ][ystr(smallestdistance return 'treasure detected at distance o...
7,630
def showinstructions() print('''instructions you are the captain of the simona treasure-hunting ship your current mission is to find the three sunken treasure chests that are lurking in the part of the ocean you are in and collect them to playenter the coordinates of the point in the ocean you wish to drop sonar device...
7,631
when you collect chestall sonar devices will update to locate the next closest sunken treasure chest press enter to continue ''' input( print( print(' !' print( print('would you like to view the instructions(yes/no)' if input(lower(startswith(' ') showinstructions( while true game setup sonardevices theboard getnewboar...
7,632
if len(thechests= print('you have found all the sunken treasure chestscongratulations and good game!' break sonardevices - if sonardevices = print('we\'ve run out of sonar devicesnow we have to turn the ship around and head' print('for home with treasure chests still out theregame over ' print(the remaining chests were...
7,633
the sonar game' board is an ascii art ocean with xand -axis coordinates around it the back tick (`and tilde (~characters are located next to the key on your keyboard will be used for the ocean waves it looks like this ~~~`~``~~~``~~~~``~`~`~`~`~~`~~~`~~`~``````~~`~``~`~~```~`~ `~`~````~~``~`~```~```~```~`~~~``~~`~~~```...
7,634
look again at the top part of the board in figure - it has plus signs instead of blank spaces so you can count the blank spaces easierfigure - the spacing used for printing the top of the game board the numbers on the first line which mark the tens position all have nine spaces between themand there are thirteen spaces...
7,635
~~`~`~~```~``~~``~~~``~~`~`~~`~`~```~```~~~```~~~~~~`~`~~~~ ```~``~`~~~`~~```~``~``~~~```~````~```~`~~`~~~~~`~``~~~~~`` `~~~~```~`~````~`~`~~``~`~~~~`~``~``~```~~```````~`~``~```` ~~`~`~~`~``~`~~~````````````````~~`````~`~~``~`~~~~`~~~`~~` the solution is easy add space only in front of all the single-digit numbers lin...
7,636
creating new game board def getnewboard() create new board data structure board [ for in range( )the main list is list of lists board append([] new board data structure is needed at the start of each new game the board data structure is list of lists of strings the first list represents the coordinate since the game' b...
7,637
create list of chest data structures (two-item lists of xy int coordinates chests [ for in range(numchests) chests append([random randint( )random randint( )] return chests the game also randomly decides where the hidden treasure chests are the treasure chests are represented as list of lists of two integers these two ...
7,638
if not isvalidmove(xy)return false in the sonar gamethe game board is updated to display number for each sonar device dropped to show how far away the closest treasure chest is so when the player makes move by giving the program an and coordinatethe board changes based on the positions of the treasure chests the makemo...
7,639
an algorithm for finding the closest treasure chest the and parameters are integers (say and )and together they represent the location on the game board where the player guessed the chests variable will have value such as [[ ][ ][ ]that value represents the locations of three treasure chests you can visualize it as the...
7,640
larger of two valuesthe absolute value of the difference of the two coordinates and the absolute value of the difference of the two coordinates that means you should subtract the sonar device' coordinate and treasure chest' coordinateand then take the absolute value of this number do the same for the sonar device' coor...
7,641
chest for cxcy in chestsif abs(cx xabs(cy )distance abs(cx xelsedistance abs(cy yif distance smallestdistancewe want the closest treasure smallestdistance distance line uses the multiple assignment trick in for loop for examplethe assignment statement spameggs [ will assign to spam and to eggs because chests is list wh...
7,642
the value has been removed from the list the remove(method removes the first occurrence of the value you pass itand only the first for exampletype the following into the interactive shellx [ remove( [ notice that only the first value was removedbut the second and third ones are still there the remove(method will cause ...
7,643
getting the player' move def enterplayermove() let the player type in their move return two-item list of int xy coordinates print('where do you want to drop the next sonar device( - - (or type quit)' while true move input( if move lower(='quit' print('thanks for playing!' sys exit(the enterplayermove(function collects ...
7,644
false 'isdigit(false 'helloisdigit(false ' isdigit(true both move[ isdigit(and move[ isdigit(must be true for the whole condition to be true the final part of line ' condition calls the isvalidmove(function to check if the xy coordinates exist on the board if the entire condition is trueline returns two-integer list of...
7,645
press enter to continue ''' input(the showinstructions(is couple of print(calls that print multi-line strings the input(function gives the player chance to press enter before printing the next string this is because the idle window can only show so much text at time print('''for examplehere is treasure chest (the cloca...
7,646
print(' !' print( print('would you like to view the instructions(yes/no)' if input(lower(startswith(' ') showinstructions(the expression input(lower(startswith(' 'asks the player if they want to see the instructionsand evaluates to true if the player typed in string that began with 'yor 'yif soshowinstructions(is calle...
7,647
if sonardevices extrassonar ' elseextrassonar ' if len(thechests extraschest ' elseextraschest ' print('you have % sonar device% left % treasure chest% remaining (sonardevicesextrassonarlen(thechests)extraschest)line ' while loop executes as long as the player has sonar devices remaining line prints message telling the...
7,648
if makemove(returns the value falsethen there was problem with the and values you passed it the continue statement will send the execution back to the start of the while loop on line to ask the player for xy coordinates again finding sunken treasure chest elseif moveresult ='you have found sunken treasure chest!'update...
7,649
checking if the player has lost sonardevices - line is the last line of the while loop that started on line decrement the sonardevices variable because the player has used one if the player keeps missing the treasure chestseventually sonardevices will be reduced to after this lineexecution jumps back up to line so it c...
7,650
summary remember how our tic tac toe game numbered the spaces on the tic tac toe board through this sort of coordinate system might have been okay for board with less than ten spaces but the sonar board has spacesthe cartesian coordinate system we learned in the last really makes all these spaces manageableespecially w...
7,651
caesar cipher topics covered in this cryptography and ciphers encrypting and decrypting ciphertextplaintextkeysand symbols the caesar cipher ascii ordinal values the chr(and ord(functions the isalpha(string method the isupper(and islower(string methods cryptanalysis the brute force technique the program in this isn' re...
7,652
understand what the original plaintext was just by looking at the ciphertext here is the previous example encrypted into ciphertextyvccf kyvivkyv bvpj kf kyv yfljv riv yzuuve leuvi kyv wcfnvi gfk but if you know about the cipher used to encrypt the messageyou can decrypt the ciphertext back to the plaintext (decryption...
7,653
figure - the entire alphabet shifted by three spaces the number of spaces you shift is the key in the caesar cipher the example above shows the letter translations for the key if you encrypt the plaintext "howdywith key of thenthe "hbecomes "kthe letter "obecomes "rthe letter "wbecomes "zthe letter "dbecomes "gthe lett...
7,654
the capital letters "athrough "zhave the ascii numbers through the lowercase letters "athrough "zhave the ascii numbers through the numeric digits " through " have the ascii numbers through table - shows all the ascii characters and ordinals modern computers use utf- instead of ascii but utf- is backwards compatible wi...
7,655
ord(' ' chr( + 'ichr( ' chr(ord(' ')'ford(chr( ) on the third linechr( + evaluates to chr( if you look at the ascii tableyou can see that is the ordinal for the capital letter "ion the fifth linechr(ord(' ')evaluates to chr( which evaluates to 'fthe ord(and chr(functions are the opposite of each other sample run of cae...
7,656
gur fxl nobir gur cbeg jnf gur pbybe bs gryrivfvbagharq gb qrnq punaary enter the key number ( - your translated text isrfc qiw yzmtc rfc nmpr uyq rfc amjmp md rcjctgqgmlrslcb rm bcyb afyllcj source code of caesar cipher here is the source code for the caesar cipher program after you type this code insave the file as c...
7,657
num ord(symbol num +key if symbol isupper() if num ord(' ') num - elif num ord(' ') num + elif symbol islower() if num ord(' ') num - elif num ord(' ') num + translated +chr(num else translated +symbol return translated mode getmode( message getmessage( key getkey( print('your translated text is:' print(gettranslatedme...
7,658
mode input(lower(if mode in 'encrypt decrypt dsplit()return mode elseprint('enter either "encryptor "eor "decryptor " 'the getmode(function will let the user type in if they want encryption or decryption mode for the program the value returned from input(and lower(is stored in mode the if statement' condition checks if...
7,659
valid key here is one that is between the integer values and (remember that max_key_size will only ever have the value because it is constantit then returns this key line sets key to the integer version of what the user typed inso getkey(returns an integer encrypt or decrypt the message with the given key def gettransl...
7,660
as you can see'forty twoisalpha(will return false because 'forty twohas space in itwhich is non-letter character 'fortytwoisalpha(returns true because it doesn' have this space ' isalpha(returns false because both ' and ' are non-letter characters isalpha(only returns true if the string has only letter characters and i...
7,661
' islower(false 'isupper(false 'islower(false encrypting or decrypting each letter if symbol isupper()if num ord(' ')num - elif num ord(' ')num + line checks if the symbol is an uppercase letter if sothere are two special cases to worry about what if symbol was 'zand key was if that were the casethe value of num here w...
7,662
if the symbol was not an uppercase or lowercase letterthen line concatenates the original symbol to the translated string thereforespacesnumberspunctuation marksand other characters won' be encrypted or decrypted return translated the last line in the gettranslatedmessage(function returns the translated string the star...
7,663
brute force is the technique of trying every possible key until you find the correct one because there are only possible keysit would be easy for cryptanalyst to write hacking program than decrypts with every possible key then they could look for the key that decrypts to plain english let' add brute force feature to th...
7,664
this program will print every possible translation of the message (including the key number used in the translationhere is sample run of this modified programdo you wish to encrypt or decrypt or brute force messagebrute enter your messagelwcjba uig vwb jm xtmiaivbjcb kmzbiqvbg qa ijaczl your translated text is kvbiaz t...
7,665
summary computers are good at doing mathematics when we create system to translate some piece of information into numbers (such as we do with text and ordinals or with space and coordinate systems)computer programs can process these numbers quickly and efficiently but while our caesar cipher program here can encrypt me...
7,666
reversi topics covered in this the bool(function how to play reversi in this we'll make game called reversi (also called othelloreversi is board game that is played on gridso we'll use cartesian coordinate system with xy coordinates it is game played with two players our version of the game will have computer ai that i...
7,667
the black tile at is between the new white tile and the existing white tile at that black tile is flipped over and becomes new white tilemaking the board look like figure - black makes similar move nextplacing black tile on which flips the white tile at this results in board that looks like figure - figure - white' mov...
7,668
each player can quickly flip many tiles on the board in one or two moves players must always make move that captures at least one tile the game ends when player either cannot make moveor the board is completely full the player with the most tiles of their color wins the ai we make for this game will simply look for any...
7,669
+---+---+---+---+---+---+---+---you have points the computer has points enter your moveor type quit to end the gameor hints to turn off/on hints +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+-...
7,670
+---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+---you have points the computer has points enter your moveor...
7,671
+---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+---source code of reversi r...
7,672
if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at reversi py reversi import random import sys def drawboard(board) this function prints out the board that it was passed returns none hline +---+---+---+---+---+---+---+---+ vline | print( ' print(hline fo...
7,673
return board def isvalidmove(boardtilexstartystart) returns false if the player' move on space xstartystart is invalid if it is valid movereturns list of spaces that would become the player' if they made move here if board[xstart][ystart!or not isonboard(xstartystart) return false board[xstart][ystarttile temporarily s...
7,674
break tilestoflip append([xy] board[xstart][ystartrestore the empty space if len(tilestoflip= if no tiles were flippedthis is not valid move return false return tilestoflip def isonboard(xy) returns true if the coordinates are located on the board return > and and <= def getboardwithvalidmoves(boardtile) returns new bo...
7,675
oscore + return {' ':xscore' ':oscore def enterplayertile() lets the player type which tile they want to be returns list with the player' tile as the first itemand the computer' tile as the second tile ' while not (tile ='xor tile =' ') print('do you want to be or ?' tile input(upper( the first element in the list is t...
7,676
board[ ][ytile return true def getboardcopy(board) make duplicate of the board list and return the duplicate dupeboard getnewboard( for in range( ) for in range( ) dupeboard[ ][yboard[ ][ return dupeboard def isoncorner(xy) returns true if the position is in one of the four corners return ( = and = or ( = and = or ( = ...
7,677
return [xy def getcomputermove(boardcomputertile) given board and the computer' tiledetermine where to move and return that move as [xylist possiblemoves getvalidmoves(boardcomputertile randomize the order of the possible moves random shuffle(possiblemoves always go for corner if available for xy in possiblemoves if is...
7,678
while true if turn ='player' player' turn if showhints validmovesboard getboardwithvalidmoves(mainboardplayertile drawboard(validmovesboard else drawboard(mainboard showpoints(playertilecomputertile move getplayermove(mainboardplayertile if move ='quit' print('thanks for playing!' sys exit(terminate the program elif mo...
7,679
elif scores[playertilescores[computertile] print('you lost the computer beat you by % points (scores[computertilescores[playertile]) else print('the game was tie!' if not playagain() break how the code works the game board data structure before getting into the codelet' figure out the board' data structure this data st...
7,680
the drawboard(function will print the current game board based on the data structure in board notice that each square of the board looks like this (there could also be ' ''or string instead of the ' ')+--- +---since the horizontal line is printed over and over againline stores it in constant variable named hline this w...
7,681
+---+---+---+---+---+---+---+---when the for loop on line prints the row eight timesit forms the entire board (of coursesome of the spaces on the board will have 'oor instead of ' ') +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+...
7,682
for in range( )for in range( )board[ ][yline and have nested loops to set the board data structure to be all single-space strings this makes blank reversi board the resetboard(function is called as part of starting new game setting up the starting pieces starting piecesboard[ ][ 'xboard[ ][ 'oboard[ ][ 'oboard[ ][ 'xat...
7,683
checking if move is valid def isvalidmove(boardtilexstartystart) returns false if the player' move on space xstartystart is invalid if it is valid movereturns list of spaces that would become the player' if they made move here if board[xstart][ystart!or not isonboard(xstartystart) return false board[xstart][ystarttile ...
7,684
because the coordinates increase as you go to the rightyou can "moveto the right by adding to the coordinate so the [ list adds to the coordinate and to the coordinateresulting in "movementto the right moving to the left is the oppositeyou would subtract (that isadd - from the coordinate but to move diagonallyyou need ...
7,685
piece if isonboard(xyand board[ ][ =othertilethere is piece belonging to the other player next to our +xdirection +ydirection if not isonboard(xy)continue rememberin order for this to be valid movethe first step in this direction must be on the board and must be occupied by the other player' tile otherwise there aren' ...
7,686
-xdirection -ydirection if =xstart and =ystartbreak tilestoflip append([xy]line ' while loop stops looping when the code has reached the end of the othertile tiles line checks if this space on the board holds one of our tiles if it doesthen the move originally passed to isvalidmove(is valid line loops by moving and in ...
7,687
checks if an and coordinate is actually on the game board for examplean coordinate of and coordinate of would not be on the board since coordinates only go up to getting list with all valid moves def getboardwithvalidmoves(boardtile) returns new board with marking the valid moves the given player can make dupeboard get...
7,688
the bool(function the bool(is similar to the int(and str(functions it returns the boolean value form of the value passed to it most data types have one value that is considered the false value for that data type every other value is consider true for examplethe integer the floating point number the empty stringthe empt...
7,689
oscore for in range( )for in range( )if board[ ][ =' 'xscore + if board[ ][ =' 'oscore + return {' ':xscore' ':oscorethe getscoreofboard(function uses nested for loops to check all spaces on the board ( rows times columns per row is spacesand see which tile (if anyis on them for each 'xtilethe code increments xscore on...
7,690
if random randint( = return 'computerelsereturn 'playerthe whogoesfirst(function randomly selects who goes firstand returns either the string 'computeror the string 'playerasking the player to play again def playagain() this function returns true if the player wants to play againotherwise it returns false print('do you...
7,691
return true on lines and if the return value of isvalidmove((now stored in tilestoflipwas falsethen makemove(will also return false otherwiseisvalidmove(returns list of spaces on the board to put down the tiles (the 'xor 'ostring in tileline sets the space that the player has moved on line ' for loop sets all the tiles...
7,692
getting the player' move def getplayermove(boardplayertile) let the player type in their move returns the move as [xy(or returns the strings 'hintsor 'quit' digits to ' split(the getplayermove(function is called to let the player type in the coordinates of their next move (and check if the move is validthe player can a...
7,693
the game is expecting that the player would have typed in the xy coordinates of their move as two numbers without anything between them line first checks that the size of the string the player typed in is after thatit also checks that both move[ (the first character in the stringand move[ (the second character in the s...
7,694
getcomputermove(and is where the ai algorithm is implemented normally you use the results from getvalidmoves(for hints mode hints mode will print period characters on the board to show the player all the potential moves they can make but if getvalidmoves(is called with the computer ai' tile (in computertile)it will als...
7,695
set to the highest scoring move the code has found so farand bestscore is set to the best move' score when the code in the loop finds move that scores higher than bestscoreline to will store that move and score as the new values in bestmove and bestscore simulate all possible moves on duplicate board data structures be...
7,696
showpoints(calls the getscoreofboard(function and then prints the player' and computer' scores remember that getscoreofboard(returns dictionary with the keys 'xand 'oand values of the scores for the and players that' all the functions for the reversi game the code starting on line will implement the actual game and cal...
7,697
drawboard(mainboardshowpoints(playertilecomputertilethe while loop that starts on line will keep looping each time the player or computer takes turn the execution will break out of this loop when the current game is over line has an if statement whose body has the code that runs if it is the player' turn (the else-bloc...
7,698
if the player typed in the string 'hintsfor their movethen getplayermove(would have returned the string 'hintsin that caseyou want to turn hints mode on (if it was offor off (if it was onthe showhints not showhints assignment statement on line handles both of these casesbecause not false evaluates to true and not true ...
7,699
call to print string before call to input()you can do the same thing by passing the string to print to input(after the player has looked at the board and pressed enterline calls getcomputermove(to get the xy coordinates of the computer' next move these coordinates are stored in variables and using multiple assignment f...