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 not operator reverses the boolean valueand the break statement executes that breaks the execution out of the while loop that was started on line but since there are no more lines of code after that while-blockthe program terminates summary creating program that can play game comes down to carefully considering all the possible situations the ai can be in and how it should respond in each of those situations the tic tac toe ai is simple because there are not many possible moves in tic tac toe compared to game like chess or checkers our ai checks if any possible move can allow itself to win otherwiseit checks if it must block the player' move then the ai simply chooses any available corner spacethen the center spacethen the side spaces this is simple algorithm for the computer to follow the key to implementing our ai is by making copies of the board data and simulating moves on the copy that waythe ai code can see if move results in win or loss then the ai can make that move on the real board this type of simulation is effective at predicting what is good move or not post questions to |
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 assignment operators and string interpolation these things don' let you do anything you couldn' do beforebut they are nice shortcuts to make coding easier bagels is deduction game you can play with friend your friend thinks up random -digit number with no repeating digitsand you try to guess what the number is after each guessyour friend gives you three types of cluesbagels none of the three digits you guessed is in the secret number pico one of the digits is in the secret numberbut your guess has the digit in the wrong place fermi your guess has correct digit in the correct place you can get multiple clues after each guess if the secret number is and your guess is the clues would be "fermi pico picothe provides "fermiand the and provide "pico picosample run of bagels am thinking of -digit number try to guess what it is here are some clueswhen saythat meanspico one digit is correct but in the wrong position fermi one digit is correct and in the right position bagels no digit is correct have thought up number you have guesses to get it guess # |
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 def getsecretnum(numdigits) returns string that is numdigits longmade up of unique random digits numbers list(range( ) random shuffle(numbers secretnum ' for in range(numdigits) secretnum +str(numbers[ ] return secretnum def getclues(guesssecretnum) returns string with the picofermibagels clues to the user if guess =secretnumpost questions to |
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 for in num if not in ' split() return false return true def playagain() this function returns true if the player wants to play againotherwise it returns false print('do you want to play again(yes or no)' return input(lower(startswith(' ' numdigits maxguess print(' am thinking of % -digit number try to guess what it is (numdigits) print('here are some clues:' print('when saythat means:' print(pico one digit is correct but in the wrong position ' print(fermi one digit is correct and in the right position ' print(bagels no digit is correct ' while true secretnum getsecretnum(numdigits |
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('you ran out of guesses the answer was % (secretnum) if not playagain() break designing the program the flow chart in figure - describes what happens in this gameand in what order they can happen how the code works import random def getsecretnum(numdigits) returns string that is numdigits longmade up of unique random digits at the start of the programimport the random module then define function named getsecretnum(the function makes secret number that has only unique digits in it instead of only -digit secret numbersthe numdigits parameter lets the function make secret number with any number of digits for exampleyou can make secret number of four or six digits by passing or for numdigits post questions to |
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 the order of list' items this function doesn' return valuebut rather modifies the list you pass it "in placethis is similar to the way the makemove(function in the tic tac toe modified the list it was passed in placerather than return new list with the change this is why you do not write code like numbers random shuffle(numberstry experimenting with the random shuffle(function by entering the following code into the interactive shellimport random spam list(range( )print(spam |
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 number from the shuffled digits secretnum 'for in range(numdigits)secretnum +str(numbers[ ]return secretnum the secret number will be string of the first numdigits digits of the shuffled list of integers for exampleif the shuffled list in numbers is [ and numdigits was then you' want the string returned by getsecretnum(to be ' to do thisthe secretnum variable starts out as blank string the for loop on line iterates numdigits number of times on each iteration through the loopthe integer at index is pulled from the shuffled listconverted to stringand concatenated to the end of secretnum for exampleif numbers refers to the list [ ]then on the first iterationnumbers[ (that is will be passed to str()which in turn returns ' which is concatenated to the end of secretnum on the second iterationthe same happens with numbers[ (that is and on the third iteration the same happens with numbers[ (that is the final value of secretnum that is returned is ' notice that secretnum in this function contains stringnot an integer this may seem oddbut remember that you cannot concatenate integers the expression evaluates to but what you want is ' ' ' 'which evaluates to ' post questions to |
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 the variable name the following code does the same thing as the above codespam spam + like spam spam eggs 'hello eggs +'world!like eggs eggs 'world!there are other augmented assignment operators as well try entering the following into the interactive shellspam spam - spam spam * spam spam / spam calculating the clues to give def getclues(guesssecretnum) returns string with the picofermibagels clues to the user if guess =secretnum return 'you got it!the getclues(function will return string with the fermipicoand bagels clues depending on the guess and secretnum parameters the most obvious and easiest step is to check if the guess is the same as the secret number in that caseline returns 'you got it! |
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 through each possible index in guess and secretnum the strings in both variables will be the same lengthso the line could have used either len(guessor len(secretnumand work the same as the value of changes from to to and so online checks if the firstsecondthirdetc letter of guess is the same as the number in the same index of secretnum if soline will add string 'fermito clue otherwiseline will check if the number at the ith position in guess exists anywhere in secretnum if soyou know that the number is somewhere in the secret number but not in the same position line will then add 'picoto clue if len(clue= return 'bagelsif the clue list is empty after the loopthen you know that there are no correct digits at all in guess in this caseline returns the string 'bagelsas the only clue the sort(list method clue sort(lists have method named sort(that rearranges the items in the list to be in alphabetical or numerical order try entering the following into the interactive shellspam ['cat''dog''bat''anteater'spam sort(spam ['anteater''bat''cat''dog'spam [ spam sort(spam [ post questions to |
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 then the line return spam the reason you want to sort the clue list is to get rid of extra information based on the order of the clues if clue was ['pico''fermi''pico']then that would tell the player that the center digit of the guess is in the correct position since the other two clues are both picothe player would know that all they have to do is swap the first and third digit to get the secret number if the clues are always sorted in alphabetical orderthe player can' be sure which number the fermi clue refers this is what we want for the game the join(string method return join(cluethe join(string method returns list of strings as single string joined together the string that the method is called on (on line this is single space'appears between each string in the list for an exampleenter the following into the interactive shelljoin(['my''name''is''zophie']'my name is zophie'join(['life''the universe''and everything']'lifethe universeand everythingso the string that is returned on line is each string in clue combined together with single space between each string the join(string method is sort of like the opposite of the split(string method while split(returns list from split up stringjoin(returns string from combined list checking if string has only numbers def isonlydigits(num) returns true if num is string made up only of digits otherwise returns false if num ='' return false |
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-blockthe code checks if doesn' exist in the list returned by ' split((the return value from split(is equivalent to [' '' '' '' '' '' '' '' '' '' 'but is easier to type if it doesn'tyou know there' non-digit character in num in that caseline returns false if execution continues past the for loopthen you know that every character in num is digit in that caseline returns true finding out if the player wants to play again def playagain() this function returns true if the player wants to play againotherwise it returns false print('do you want to play again(yes or no)' return input(lower(startswith(' 'the playagain(function is the same one you used in hangman and tic tac toe the long expression on line evaluates to either true or false based on the answer given by the player the start of the game numdigits maxguess print(' am thinking of % -digit number try to guess what it is (numdigits) print('here are some clues:' print('when saythat means:' print(pico one digit is correct but in the wrong position ' print(fermi one digit is correct and in the right position ' print(bagels no digit is correct 'post questions to |
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 easy to change the number of guesses or secret number digits just change line or and the rest of the program will still work without any more changes the print(function calls will tell the player the rules of the game and what the picofermiand bagels clues mean line ' print(call has (numdigitsadded to the end and % inside the string this is technique known as string interpolation string interpolation string interpolation is coding shortcut normallyif you want to use the string values inside variables in another stringyou have to use the concatenation operatorname 'aliceevent 'partywhere 'the poolday 'saturdaytime ' : pmprint('helloname will you go to the event at where this day at time '?'helloalice will you go to the party at the pool this saturday at : pmas you can seeit can be hard to type line that concatenates several strings insteadyou can use string interpolationwhich lets you put placeholders like % these placeholders are called conversion specifiers then put all the variable names at the end each % is replaced with variable at the end of the line for examplethe following code does the same thing as the previous codename 'aliceevent 'partywhere 'the poolday 'saturdaytime ' : pmprint('hello% will you go to the % at % this % at % ?(nameeventwheredaytime)helloalice will you go to the party at the pool this saturday at : pm |
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 interpolation works with any data typenot just strings all values are automatically converted to the string data type if you concatenated an integer to stringyou' get this errorspam print('spam =spamtraceback (most recent call last)file ""line in typeerrorcan' convert 'intobject to str implicitly string concatenation can only combine two stringsbut spam is an integer you would have to remember to put str(spaminstead of spam but with string interpolationthis conversion to strings is done for you try entering this into the interactive shellspam print('spam is % (spam)spam is string interpolation is also known as string formatting creating the secret number while true secretnum getsecretnum(numdigits print(' have thought up number you have % guesses to get it (maxguess) numguesses while numguesses <maxguessline is an infinite while loop that has condition of true so it will loop forever until break statement is executed inside the infinite loopyou get secret number from the getsecretnum(functionpassing it numdigits to tell how many digits you want the secret number to have this secret number is assigned to secretnum rememberthe value in secretnum is string not an integer line tells the player how many digits is in the secret number by using string interpolation instead of string concatenation line sets variable numguesses to to mark this is as the first post questions to |
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 asking the player for guess until the player enters valid guess valid guess has only digits and the same number of digits as the secret number this is what the while loop that starts on line is for the guess variable is set to the blank string on line so the while loop' condition is false the first time it is checkedensuring the execution enters the loop getting the clues for the player' guess clue getclues(guesssecretnumprint(cluenumguesses + after execution gets past the while loop that started on line guess contains valid guess pass this and secretnum to the getclues(function it returns string of the clueswhich are displayed to the player on line line increments numguesses using the augmented assignment operator for addition checking if the player won or lost notice that this second while loop on line is inside another while loop that started on line these loops-inside-loops are called nested loops any break or continue statements will only break or continue out of the innermost loopand not any of the outer loop if guess =secretnum break if numguesses maxguess print('you ran out of guesses the answer was % (secretnum) |
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 back to the while loop on line where it lets the player have another guess if the player ran out of guesses (or it broke out of the loop with the break statement on line )then execution would proceed past the loop and to line asking the player to play again if not playagain()break line asks the player if they want to play again by calling the playagain(function if playagain(returns falsebreak out of the while loop that started on line since there' no more code after this loopthe program terminates if playagain(returned truethen the execution would not execute the break statement and execution would jump back to line the program generates new secret number so the player can play new game summary bagels is simple game to program but can be difficult to win at but if you keep playingyou'll eventually discover better ways to guess and make use of the clues the game gives you this is much like how you'll get better at programming you more you keep at it this introduced few new functions and methods (random shuffle()sort()and join())along with couple handy shortcuts an augmented assignment operators involve less typing when you want to change variable' relative value such as in spam spam which can be shortened to spam + string interpolation can make your code much more readable by placing % (called conversion specifierinside the string instead of using many string concatenation operations the next isn' about programming directlybut will be necessary for the games we want to create in the later of this book we will learn about the math concepts of cartesian coordinates and negative numbers these are used in the sonarreversiand dodger gamesbut cartesian coordinates and negative numbers are used in many games if you already know about these conceptsgive the next brief read anyway to refresh yourself post questions to |
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 screen can move left or right and up or down these two directions make up two-dimensionalor dspace games with objects moving around two-dimensional computer screen need way to translate place on the screen into integers the program can deal with this is where the cartesian coordinate system comes in the coordinates are numbers for specific point on the screen these numbers can be stored as integers in your program' variables grids and cartesian coordinates figure - sample chessboard with black knight at and white knight at |
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 figure - is located at the point and the black knight is located at point this labeled chessboard is cartesian coordinate system by using row label and column labelyou can give coordinate that is for one and only one space on the board if you've learned about cartesian coordinate systems in math classyou may know that numbers are used for both the rows and columns that chessboard would look like figure - figure - the same chessboard but with numeric coordinates for both rows and columns the numbers going left and right along the columns are part of the -axis the numbers going up and down along the rows are part of the -axis coordinates are always described with the xcoordinate firstfollowed by the -coordinate in figure - the white knight is located at the coordinate and not the black knight is located at the coordinate which is not to be confused with notice that for the black knight to move to the white knight' positionthe black knight must move up two spaces and to the right by four spaces but you don' need to look at the board to figure this out if you know the white knight is located at and the black knight is located at then you can use subtraction to figure out this information post questions to |
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 out the distances between two coordinates negative numbers cartesian coordinates use negative numbers negative numbers are numbers that are smaller than zero minus sign in front of number shows it is negative - is smaller than and - is smaller than - if you think of regular numbers (called positive numbersas starting from and increasingyou can think of negative numbers as starting from - and decreasing itself isn' positive or negative in figure - you can see the positive numbers increasing to the right and the negative numbers decreasing to the left on number line figure - number line the number line is useful to see subtraction and addition done with negative numbers the expression can be thought of as the white knight starting at position and moving spaces over to the right (addition means increasingwhich is in the right directionfigure - moving the white knight to the right adds to the coordinate as you can see in figure - the white knight ends up at position this makes sensebecause is subtraction is done by moving the white knight to the left subtraction means decreasingwhich is in the left direction would be the white knight starting at position and moving spaces to the leftlike in figure - |
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 knight moves to the right the expression - - would be equal to - the knight starts at - and moves to the right by spaces notice that - - has the same answer as - figure - even if the white knight starts at negative coordinatemoving right still adds to the coordinate figure - putting two number lines together creates cartesian coordinate system post questions to |
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 (or adding negative numberwould move the knight down the coordinate is called the origin math tricks subtracting and adding negative numbers is easy when you have number line in front of you it can also be easy without number line too here are three tricks to help you add and subtract negative numbers by yourself trick " minus eats the plus sign on its leftwhen you see minus sign with plus sign on the leftyou can replace the plus sign with minus sign imagine the minus sign "eatingthe plus sign to its left the answer is still the samebecause adding negative value is the same as subtracting positive value - and both evaluate to figure - trick adding positive and negative number trick "two minuses combine into pluswhen you see the two minus signs next to each other without number between themthey can combine into plus sign the answer is still the samebecause subtracting negative value is the same as adding positive value |
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 if you swap the numbers for addition figure - trick the commutative property of addition say you are adding negative number and positive numberlike - because you are adding numbersyou can swap the order of the numbers without changing the answer - is the same as - then when you look at - you see that the minus sign can eat the plus sign to its leftand the problem becomes but this means that - is also you've rearranged the problem to have the same answerbut made it easier for us to solve without using calculator or computer post questions to |
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 of (which is positiveis just you can figure out the distance between two objects by subtracting their positions and taking the absolute value of the difference imagine that the white knight is at position and the black knight is at position - the distance would be since - is and the absolute value of is it works no matter what the order of the numbers is - (that isnegative two minus fouris - and the absolute value of - is also python' abs(function returns the absolute value of an integer try entering the following into the interactive shellabs(- abs( abs(- |
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 computer graphics use this coordinate systemand you will use it in this book' games summary most programming doesn' require understanding lot of math up until this we've been getting by on simple addition and multiplication cartesian coordinate systems are needed to describe where in two-dimensional area certain position is coordinates have two numbersthe -coordinate and the -coordinate the -axis runs left and right and the -axis runs up and down on computer screenorigin is in the topleft corner and the coordinates increase going right and down the three tricks you learned in this make it easy to add positive and negative integers the first trick is that minus sign will eat the plus sign on its left the second trick is that two minuses next to each other will combine into plus sign the third trick is that you can swap the position of the numbers you are adding for the rest of the bookwe will use the concepts from this in our games because they have two-dimensional areas in them all graphical games require understanding how cartesian coordinates work post questions to |
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 those that contain lists of lists as the games you program become more complicatedyou'll need to organize your data in data structures in this gamethe player places sonar devices at various places in the ocean to locate sunken treasure chests sonar is technology that ships use to locate objects under the sea the sonar devices (in this gamewill tell the player how far away the closest treasure chest isbut not in what direction but by placing multiple sonar devices downthe player can figure out where the treasure chest is there are three chests to collectbut the player has only sixteen sonar devices to use to find them imagine that you could not see the treasure chest in the following picture because each sonar device can only find the distancenot directionthe possible places the treasure could be is anywhere in square ring around the sonar device (see figure - figure - the sonar device' square ring touches the (hiddentreasure chest |
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 sonar treasure hunt would you like to view the instructions(yes/nono `~~~`~~~`~`~~`~~~~~`~``~~~~`~`~~~`~``~``~~````~`~```~`~~~~` ~`~~~```~~~~`~`~~`~``~`~~```~`~`~~`~`~~~~~~`~`````~`~~`~~~~ `~``~``~~~`~``~`~`~``~`````~~~~~~~~~`~`~~`~``~~~~~```~~`~`` ``~`~~``~`~``~`~`~`~~`~`~~`~`~``~~~`~``~````~``````~~~~``~` ``~~`~~~``~``~~````~`~`~`~``~~~``~~```~`~~`~~`~`~`~~`~~~~`` ~~```~~~`~`~~``~`~``~```~`~~`~~~~~`~~``~`~`~~~`~~`~`~`~`~~~ ``~~`````~~~~`~`~~~```~~~~`~~`~~`~~```~~`~~~`~~~``~`~~~``~~ `~`````````~```~``~``~~`~~~~`~~``~``~~~```~`~~`~``~``~~```~ `~````~```~`~~`~~~`~~``~~~``~`~``~~~``~`~`````~`~~```~`~~~~ ~```~~`~`~``~``~~``~``~```~`~``~~~~`~`~`~~~`~`~`~`~~~``~~`` ```~`~```~``~``~`~~`~``~````~``~~~`~~`~~``~~~~`~~~`~`~~```` ```~```~~~`~```~~`~~~`~`````~`~~`~`~~`~~`~`~~`~~~````~````~ ~~~`~`~~~``~~~~~~`~~~``~`~`~~`~`~~`~```~~~```~~`~~`~``~``~` `~~````~~``~```~~~`~```~`~~~~~~~~~`~~``~~~~~`````~`~`~``~~~ `~~`~`~````~```~`~`~```~~`~~~~`~```~``~``~``~~~````~~`````` you have sonar devices left treasure chests remaining where do you want to drop the next sonar device( - - (or type quit post questions to |
7,625 | `~~~`~~~`~`~~`~~~~~`~``~~~~`~`~~~`~``~``~~````~`~```~`~~~~` ~`~~~```~~~~`~`~~`~``~`~~```~`~`~~`~`~~~~~~`~`````~`~~`~~~~ `~``~``~~~`~``~`~`~``~`````~~~~~~~~~`~`~~`~``~~~~~```~~`~`` ``~`~~``~`~``~`~`~`~~`~`~~`~`~``~~~`~``~````~``````~~~~``~` ``~~`~~~``~``~~````~`~`~`~``~~~``~~```~`~~`~~`~`~`~~`~~~~`` ~~```~~~`~`~~``~`~``~```~`~~`~~~~~`~~``~`~`~~~`~~`~`~`~`~~~ ``~~`````~~~~`~`~~~```~~~~`~~`~~`~~```~~`~~~`~~~``~`~~~``~~ `~`````````~```~``~``~~`~~~~`~~``~``~~~```~`~~`~``~``~~```~ `~````~```~`~~`~~~`~~``~~~``~`~``~~~``~`~`````~`~~```~`~~~~ ~```~~`~`~``~``~~``~``~```~`~``~~~~`~`~`~~~`~`~`~`~~~``~~`` ```~`~```~ `~``~`~~`~``~````~``~~~`~~`~~``~~~~`~~~`~`~~```` ```~```~~~`~```~~`~~~`~`````~`~~`~`~~`~~`~`~~`~~~````~````~ ~~~`~`~~~``~~~~~~`~~~``~`~`~~`~`~~`~```~~~```~~`~~`~``~``~` `~~````~~``~```~~~`~```~`~~~~~~~~~`~~``~~~~~`````~`~`~``~~~ `~~`~`~````~```~`~`~```~~`~~~~`~```~``~``~``~~~````~~`````` treasure detected at distance of from the sonar device you have sonar devices left treasure chests remaining where do you want to drop the next sonar device( - - (or type quit `~~~`~~~`~`~~`~~~~~`~``~~~~`~`~~~`~``~``~~````~`~```~`~~~~` ~`~~~```~~~~`~`~~`~``~`~~```~`~`~~`~`~~~~~~`~`````~`~~`~~~~ `~``~``~~~`~``~`~`~``~`````~~~~~~~~~`~`~~`~``~~~~~```~~`~`` ``~`~~``~`~``~`~`~`~~`~`~~`~`~``~~~`~``~````~``````~~~~``~` ``~~`~~~``~``~~````~`~`~`~``~~~``~~```~`~~`~~`~`~`~~`~~~~`` ~~```~~~`~`~~``~`~``~```~`~~`~~~~~`~~``~`~`~~~`~~`~`~`~`~~~ ``~~`````~~~~`~ ~~~```~~~~`~~`~~`~~```~~`~~~`~~~``~`~~~``~~ `~`````````~```~``~``~~`~~~~`~~``~``~~~```~`~~`~``~``~~```~ `~````~```~`~~`~~~`~~``~~~``~`~``~~~``~`~`````~`~~```~`~~~~ ~```~~`~`~``~``~~``~``~```~`~``~~~~`~`~`~~~`~`~`~`~~~``~~`` ```~`~```~ `~``~`~~`~``~````~``~~~`~~`~~``~~~~`~~~`~`~~```` ```~```~~~`~```~~`~~~`~`````~`~~`~`~~`~~`~`~~`~~~````~````~ ~~~`~`~~~``~~~~~~`~~~``~`~`~~`~`~~`~```~~~```~~`~~`~``~``~` `~~````~~``~```~~~`~```~`~~~~~~~~~`~~``~~~~~`````~`~`~``~~~ `~~`~`~````~```~`~`~```~~`~~~~`~```~``~``~``~~~````~~`````` treasure detected at distance of from the sonar device you have sonar devices left treasure chests remaining where do you want to drop the next sonar device( - - (or type quit |
7,626 | `~~~`~~~`~`~~`~~~~~`~``~~~~`~`~~~`~``~``~~````~`~```~`~~~~` ~`~~~```~~~~`~`~~`~``~`~~```~`~`~~`~`~~~~~~`~`````~`~~`~~~~ `~``~``~~~`~``~`~`~``~`````~~~~~~~~~`~`~~`~``~~~~~```~~`~`` ``~`~~``~`~``~`~`~`~~`~`~~`~`~``~~~`~``~````~``````~~~~``~` ``~~`~~~``~``~~````~`~`~`~``~~~``~~```~`~~`~~`~`~`~~`~~~~`` ~~```~~~`~`~~``~`~``~```~`~~`~~~~~`~~``~`~`~~~`~~`~`~`~`~~~ ``~~`````~~~~`~ ~~~```~~~~`~~`~~`~~```~~`~~~`~~~``~`~~~``~~ `~`````````~```~``~``~~`~~~~`~~``~``~~~```~`~~`~``~``~~```~ `~````~```~`~~`~~~`~~``~~~``~`~``~~~``~`~`````~`~~```~`~~~~ ~```~~`~`~``~``~~``~``~```~`~``~~~~`~`~`~~~`~`~`~`~~~``~~`` ```~`~```~ `~`` `~~`~``~````~``~~~`~~`~~``~~~~`~~~`~`~~```` ```~```~~~`~```~~`~~~`~`````~`~~`~`~~`~~`~`~~`~~~````~````~ ~~~`~`~~~``~~~~~~`~~~``~`~`~~`~`~~`~```~~~```~~`~~`~``~``~` `~~````~~``~```~~~`~```~`~~~~~~~~~`~~``~~~~~`````~`~`~``~~~ `~~`~`~````~```~`~`~```~~`~~~~`~```~``~``~``~~~````~~`````` you have found sunken treasure chestyou have sonar devices left treasure chests remaining where do you want to drop the next sonar device( - - (or type quitskipped over for brevity `~~~`~~~`~`~~`~~~~~`~``~~~~`~`~~~`~``~``~~````~`~```~`~~~~` ~`~~~```~~~~`~`~~`~``~`~~```~ ~`~~`~`~~~~~~`~`````~`~~`~~~~ `~``~``~~~`~``~`~`~``~`````~~ ~~~ ~~`~`~~`~``~~~~~```~~`~`` ``~ ~~`` `~``~`~`~`~~`~`~~`~`~``~~~`~` ~````~``````~~~~``~` ``~~`~~~``~``~~````~`~`~`~ `~~ ``~~```~`~~`~~`~`~`~~`~~~~`` ~~```~~~`~`~~``~`~``~```~`~~`~~~~~`~~``~`~`~~~`~~`~`~`~`~~~ ``~~`````~~~~`~ ~~~```~~~~`~~`~~`~~```~~`~~~`~~~`` `~~~``~~ `~`````````~```~``~``~~`~~~~`~~``~``~~~```~`~~`~``~``~~```~ `~````~```~`~~`~~~`~~``~~~``~`~``~~~``~` ``` `~`~~```~`~~~~ ~```~~`~`~``~``~~``~``~```~ ~``~~~~`~`~`~~~`~`~`~`~~~``~~`` ```~`~```~ `~`` `~~`~``~````~``~~~`~~`~~``~~~~`~~~`~`~~```` ```~```~~~`~```~~`~~~`~`````~`~~`~`~~`~~`~`~~`~~~````~````~ ~~~`~`~~~``~~~~~~`~~~``~`~`~~`~`~~`~```~~~```~~`~~`~``~``~` `~~````~~``~```~~~`~```~`~~~~~~~~~`~~``~~~~~`````~`~`~``~~~ `~~`~`~````~```~`~`~```~~`~~~~`~```~``~``~``~~~````~~`````` treasure detected at distance of from the sonar device we've run out of sonar devicesnow we have to turn the ship around and head for home with treasure chests still out theregame over the remaining chests were herepost questions to |
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 sonar import random import sys def drawboard(board) draw the board data structure hline initial space for the numbers down the left side of the board for in range( ) hline +( str( print the numbers across the top print(hline print((' ) print( print each of the rows for in range( ) single-digit numbers need to be padded with an extra space if extraspace else extraspace ' print('% % % % (extraspaceigetrow(boardi) ) print the numbers across the bottom print( print((' ) print(hline def getrow(boardrow) |
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 different characters for the ocean to make it more readable if random randint( = board[xappend('~' else board[xappend('`' return board def getrandomchests(numchests) 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 def isvalidmove(xy) return true if the coordinates are on the boardotherwise false return > and and < def makemove(boardchestsxy) change the board data structure with sonar device character remove treasure chests from the chests list as they are found return false if this is an invalid move otherwisereturn the string of the result of this move if not isvalidmove(xy) return false smallestdistance any chest will be closer than for cxcy in chests if abs(cx xabs(cy ) distance abs(cx elsepost questions to |
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 of % from the sonar device (smallestdistance else board[ ][ ' return 'sonar did not detect anything all treasure chests out of range 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( move move split( if len(move= and move[ isdigit(and move[ isdigit(and isvalidmove(int(move[ ])int(move[ ])) return [int(move[ ])int(move[ ]) print('enter number from to spacethen number from to ' def playagain() this function returns true if the player wants to play againotherwise it returns false print('do you want to play again(yes or no)' return input(lower(startswith(' ' |
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 the sonar can find out how far away the closest chest is to it for examplethe below marks where the device was droppedand the ' represent distances of away from the device the ' represent distances of away from the device press enter to continue ''' input( print('''for examplehere is treasure chest (the clocated distance of away from the sonar device (the ) the point where the device was dropped will be marked with the treasure chests don' move around sonar devices can detect treasure chests up to distance of if all chests are out of rangethe point will be marked with if device is directly dropped on treasure chestyou have discovered the location of the chestand it will be collected the sonar device will remain there post questions to |
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 getnewboard( thechests getrandomchests( drawboard(theboard previousmoves [ while sonardevices start of turn show sonar device/chest status if sonardevices extrassonar ' elseextrassonar ' if len(thechests extraschest ' elseextraschest ' print('you have % sonar device% left % treasure chest% remaining (sonardevicesextrassonarlen(thechests)extraschest) xy enterplayermove( previousmoves append([xy]we must track all moves so that sonar devices can be updated moveresult makemove(theboardthechestsxy if moveresult =false continue else if moveresult ='you have found sunken treasure chest!' update all the sonar devices currently on the map for xy in previousmoves makemove(theboardthechestsxy drawboard(theboard print(moveresult |
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 here:' for xy in thechests print(% % (xy) if not playagain() sys exit(designing the program before trying to understand the source codeplay the game few times first to understand what is going on the sonar game uses lists of lists and other such complicated variablescalled data structures data structures are variables that store arrangements of values to represent something for examplein the tic tac toe tic tac toe board data structure was list of strings the string represented an xoor empty space and the index of the string in the list represented the space on the board the sonar game will have similar data structures for the locations of treasure chests and sonar devices how the code works sonar import random import sys lines and import modules random and sys the sys module contains the exit(functionwhich causes the program to terminate immediately this function is used later in the program drawing the game board def drawboard(board)post questions to |
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 ~~~`~``~~~``~~~~``~`~`~`~`~~`~~~`~~`~``````~~`~``~`~~```~`~ `~`~````~~``~`~```~```~```~`~~~``~~`~~~``````~`~``~~``~~`~~ ```~~~~`~`~~```~~~``~````~~`~`~~`~`~`~```~~`~``~~`~`~~~~~~` ~~~~`~~~``~```~``~~`~`~~`~`~~``~````~`~````~```~`~`~`~````` ~```~~~~~`~~````~~~~```~~~`~`~`~````~`~~`~`~~``~~`~``~`~``~ `~```~`~`~~`~~~```~~``~``````~~``~`~`~~~~`~~``~~~~~~`~```~~ ``~~`~~`~``~`````~````~~``~`~~~~`~~```~~~``~`~`~~``~~~```~~ ``~``~~~~~~```~`~```~~~``~`~``~`~~~~~~```````~~~`~~`~~`~~`~ ~~`~`~~```~``~~``~~~``~~`~`~~`~`~```~```~~~```~~~~~~`~`~~~~ ```~``~`~~~`~~```~``~``~~~```~````~```~`~~`~~~~~`~``~~~~~`` `~~~~```~`~````~`~`~~``~`~~~~`~``~``~```~~```````~`~``~```` ~~`~`~~`~``~`~~~````````````````~~`````~`~~``~`~~~~`~~~`~~` ~~`~~~~```~~~`````~~``~`~`~~``````~`~~``~```````~~``~~~`~~` `~``````~~``~`~~~```~~~~```~~`~`~~~`~```````~~`~```~``~`~~~ ~~~``~```~`````~~`~`~``~~`~``~`~~`~`~``~`~``~~``~`~``~```~~ the drawing in the drawboard(function has four steps firstcreate string variable of the line with and spaced out with wide gaps (to mark the coordinates for and on the -axisseconduse that string to display the -axis coordinates along the top of the screen thirdprint each row of the ocean along with the -axis coordinates on both sides of the screen fourthprint the -axis again at the bottom coordinates on all sides makes it easier to see coordinates for where to place sonar device drawing the -coordinates along the top draw the board data structure hline initial space for the numbers down the left side of the board for in range( ) hline +( str( |
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 in front of the lines to create this string with this line and store it in variable named hline print the numbers across the top print(hlineprint((' )print(to print the numbers across the top of the sonar boardfirst print the contents of the hline variable then on the next lineprint three spaces (so that this row lines up correctly)and then print the string ' but as shortcut you can use (' )which evaluates to the same string drawing the rows of the ocean print each of the rows for in range( )single-digit numbers need to be padded with an extra space if extraspace elseextraspace 'print('% % % % (extraspaceigetrow(boardi) )lines to print each row of ocean wavesincluding the numbers down the side to label the -axis the for loop prints rows through along with the row numbers on either side of the board there' small problem numbers with only one digit (like and so ononly take up one space when printedbut numbers with two digits (like and take up two spaces the rows won' line up if the coordinates have different sizes it will look like thispost questions to |
7,635 | ~~`~`~~```~``~~``~~~``~~`~`~~`~`~```~```~~~```~~~~~~`~`~~~~ ```~``~`~~~`~~```~``~``~~~```~````~```~`~~`~~~~~`~``~~~~~`` `~~~~```~`~````~`~`~~``~`~~~~`~``~``~```~~```````~`~``~```` ~~`~`~~`~``~`~~~````````````````~~`````~`~~``~`~~~~`~~~`~~` the solution is easy add space only in front of all the single-digit numbers lines to set the variable extraspace to either space or an empty string the extraspace variable is always printedbut only has space character in it for single-digit row numbers otherwiseit is the empty string this wayall of the rows will line up when you print them the getrow(function takes row number and returns string representing that row' ocean waves its two parameters are the board data structure stored in the board variable and row number let' look at this function next drawing the -coordinates along the bottom print the numbers across the bottom print(print((' )print(hlinelines to are similar to lines to they print the -axis coordinates at the bottom of the screen getting the state of row in the ocean def getrow(boardrow) return string from the board data structure at certain row boardrow ' for in range( ) boardrow +board[ ][row return boardrow while the board parameter is data structure for the entire ocean' wavesthe getrow(function creates string for single row first set boardrow to the blank string the -axis coordinate is passed as the row parameter the string is made by concatenating board[ ][row]board[ ][row]board[ ][row]and so on up to board[ ][rowthis is because the row contains charactersfrom index to index the for loop on line iterates over integers to on each iterationthe next character in the board data structure is copied on to the end of boardrow by the time the loop is doneboardrow has the complete row' ascii art waves and is returned |
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' board is characters acrossthis first list needs to contain lists create for loop that will append blank lists to it for in range( )each list in the main list has singlecharacter strings use different characters for the ocean to make it more readable if random randint( = board[xappend('~' else board[xappend('`'but board is more than just list of blank lists each of the lists represents an coordinate of the game board there are rows in the boardso each of these lists must have characters in them line is another for loop to add single-character strings that represent the ocean the "oceanwill be bunch of randomly chosen '~and '`strings if the return value of random randint(is add the '~string otherwise add the '`string this will give the ocean randomchoppy look to it remember that the board variable is list of listseach list having strings that means to get the string at coordinate you would access board[ ][ ]and not board[ ][ the coordinate is firstthen the coordinate return board finallythe function returns the value in the board variable creating the random treasure chests def getrandomchests(numchests)post questions to |
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 integers will be the and coordinates of single chest for exampleif the chest data structure was [[ ][ ][ ]]then this would mean there are three treasure chestsone at another chest at and third one at the numchests parameter tells the function how many treasure chests to generate line ' for loop will iterate numchests number of timesand on each iteration line appends list of two random integers the coordinate can be anywhere from to and the coordinate can be from anywhere between and the expression [random randint( )random randint( )that is passed to the append method will evaluate to list value like [ or [ or [ this list value is appended to chests determining if move is valid def isvalidmove(xy) return true if the coordinates are on the boardotherwise false return > and and < when the player types in and coordinates of where they want to drop sonar devicethey may not type invalid coordinates the coordinate must be between and and the coordinate must be between and the isvalidmove(function uses simple expression that uses and operators to ensure that each part of the condition is true if even one part is falsethen the entire expression evaluates to false this function returns this boolean value placing move on the board def makemove(boardchestsxy) change the board data structure with sonar device character remove treasure chests from the chests list as they are found return false if this is an invalid move otherwisereturn the string of the result of this move |
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 makemove(function takes four parametersthe game board data structurethe treasure chests data structureand the and coordinates line returns false if the and coordinates if was passed do not exist on the game board if isvalidmove(returns falsethen makemove(will itself return false otherwisemakemove(will return string value describing what happened in response to the moveif the coordinates land directly on the treasuremakemove(returns 'you have found sunken treasure chest!if the coordinates are within distance of or lessmakemove(returns 'treasure detected at distance of % from the sonar device (where % is replaced with the integer distanceotherwisemakemove(will return 'sonar did not detect anything all treasure chests out of range chest smallestdistance any chest will be closer than for cxcy in chestsif abs(cx xabs(cy )distance abs(cx xelsedistance abs(cy yif distance smallestdistancewe want the closest treasure smallestdistance distance given the coordinates of where the player wants to drop the sonar device and list of xy coordinates for the treasure chestsyou'll need an algorithm to find out which treasure chest is closest post questions to |
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 picture in figure - the distances form "ringsaround the sonar device located at as in figure - figure - the treasure chests that [[ ][ ][ ]represents figure - the board marked with distances from the position but how do you translate this into code for the gameyou need way to represent the square ring distance as an expression notice that the distance from an xy coordinate is always 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' coordinate and treasure chest' coordinate the larger of these two values is the distance for exampleconsider the sonar' and coordinates are and like in figure - the first treasure chest' and coordinates (that isfirst in the list [[ ][ ][ ]]are and for the coordinates evaluates to - and the absolute value of - is for the coordinates evaluates to and the absolute value of is comparing the two absolute values and the larger value is so should be the distance between the sonar device and the treasure chest at coordinates we can look at the board in figure - and see that this algorithm worksbecause the treasure chest at is in the sonar device' nd ring let' quickly compare the other two chests to see if the distances work out correctly also let' find the distance from the sonar device at and the treasure chest at abs( evaluates to abs( evaluates to is larger than so the distance from the sonar device at and the treasure chest at is let' find the distance from the sonar device at and the last treasure chest at abs( evaluates to abs( evaluates to is larger than so the distance is looking at figure - you can see all three distances worked out correctly it seems this algorithm works the distances from the sonar device to the three sunken treasure chests are and on each guessyou want to know the distance from the sonar device to the closest of the three treasure chest distances to do thisuse variable called smallestdistance let' look at the code again smallestdistance any chest will be closer than post questions to |
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 where each item in the list is itself list of two integersthe first of these integers is assigned to cx and the second integer is assigned to cy so if chests has the value [[ ][ ][ ]]cx will have the value and cy will have the value on the first iteration through the loop line determines which is largerthe absolute value of the difference of the coordinatesor the absolute value of the difference of the coordinates abs(cx xabs(cy yseems like much shorter way to say thatdoesn' itlines to assign the larger of the values to the distance variable so on each iteration of the for loopthe distance variable holds the treasure chest' distance from the sonar device but you want the smallest distance of all the treasure chests this is where the smallestdistance variable comes in whenever the distance variable is smaller than smallestdistancethen the value in distance becomes the new value of smallestdistance give smallestdistance the impossibly high value of at the beginning of the loop so that at least one of the treasure chests you found will be put into smallestdistance by the time the for loop has finishedyou know that smallestdistance holds the shortest distance between the sonar device and all of the treasure chests in the game the remove(list method the remove(list method will remove the first occurrence of value matching the passed in argument for exampletry entering the following into the interactive shellx [ remove( [ |
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 an error if you try to remove value that isn' in the listx [ remove( traceback (most recent call last)file ""line in valueerrorlist remove( ) not in list if smallestdistance = xy is directly on treasure chestchests remove([xy]return 'you have found sunken treasure chest!the only time that smallestdistance is equal to is when the sonar device' xy coordinates are the same as treasure chest' xy coordinates this means the player has correctly guessed the location of treasure chest remove this chest' two-integer list from the chests data structure with the remove(list method then the function returns 'you have found sunken treasure chest! else if smallestdistance board[ ][ystr(smallestdistance return 'treasure detected at distance of % from the sonar device (smallestdistance else board[ ][ ' return 'sonar did not detect anything all treasure chests out of range the else-block starting on line executes if smallestdistance was not which means the player didn' guess an exact location of treasure chest if the sonar device' distance was less than line marks the board with the string version of smallestdistance if notmark the board with ' post questions to |
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 the xy coordinates of the player' next move the while loop will keep asking the player for their next move until they enter valid move the player can also type in 'quitto quit the game in that caseline calls the sys exit(function to terminate the program immediately move move split( if len(move= and move[ isdigit(and move[ isdigit(and isvalidmove(int(move[ ])int(move[ ])) return [int(move[ ])int(move[ ]) print('enter number from to spacethen number from to 'assuming the player has not typed in 'quit'the code must ensure it is valid movetwo integers separated by space line calls the split(method on move as the new value of move if the player typed in value like ' 'then the list returned by split(would be [' '' '' 'in that casethe expression len(move= would be false and the entire expression evaluates immediately to false python doesn' check the rest of the expression because of short-circuiting (which was described in if the list' length is then the two values will be at indexes move[ and move[ to check if those values are numeric digits (like ' or ' ')you could use function like isonlydigits(from but python already has function that does this the string method isdigit(returns true if the string consists solely of numbers otherwise it returns false try entering the following into the interactive shell' isdigit(true 'fortyisdigit( |
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 the xy coordinates otherwisethe execution loops and the player will be asked to enter coordinates again asking the player to play again def playagain() this function returns true if the player wants to play againotherwise it returns false print('do you want to play again(yes or no)' return input(lower(startswith(' 'the playagain(function is similar to the playagain(functions in previous printing the game instructions for the player 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 the sonar can find out how far away the closest chest is to it for examplethe below marks where the device was droppedand the ' represent distances of away from the device the ' represent distances of away from the device post questions to |
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 clocated distance of away from the sonar device (the ) the point where the device was dropped will be marked with the treasure chests don' move around sonar devices can detect treasure chests up to distance of if all chests are out of rangethe point will be marked with if device is directly dropped on treasure chestyou have discovered the location of the chestand it will be collected the sonar device will remain there when you collect chestall sonar devices will update to locate the next closest sunken treasure chest press enter to continue ''' input( print(after the player presses enterthe function returns the start of the game |
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 called otherwisethe game begins while true game setup sonardevices theboard getnewboard( thechests getrandomchests( drawboard(theboard previousmoves [line ' while loop is the main loop for the program several variables are set up on lines to and are described in table - sonardevices table - variables used in the main game loop description the number of sonar devices (and turnsthe player has left theboard the board data structure used for this game thechests the list of chest data structures getrandomchests(will return list of three treasure chests at random places on the board previousmoves list of all the xy moves that the player has made in the game variable displaying the game status for the player while sonardevices start of turnshow sonar device/chest status post questions to |
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 user how many sonar devices and treasure chests are left but there' small problem if there are two or more sonar devices leftyou want to print ' sonar devicesbut if there' only one sonar device leftyou want to print ' sonar deviceleft you only want the plural form of "devicesif there are multiple sonar devices the same goes for ' treasure chestsand ' treasure chestlines through have code after the if and else statementscolon this is perfectly valid python instead of having block of code after the statementyou can use the rest of the same line to make your code more concise the two variables named extrassonar and extraschest are set to ' (spaceif there are multiple sonar devices or treasures chests otherwisethey are blank strings these variables are used on line getting the player' move xy enterplayermove( previousmoves append([xy]we must track all moves so that sonar devices can be updated moveresult makemove(theboardthechestsxy if moveresult =false continue line uses multiple assignment since enterplayermove(returns two-item list the first item in the returned list is assigned to the variable the second is assigned to the variable they are then appended to the end of the previousmoves list this means previousmoves is list of xy coordinates of each move the player makes in this game this list is used later in the program on line the xytheboardand thechests variables are all passed to the makemove(function this function will make the necessary modifications to the game board to place sonar device on the board |
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 all the sonar devices currently on the map for xy in previousmovesmakemove(theboardthechestsxydrawboard(theboardprint(moveresultif makemove(didn' return the value falseit would have returned string of the results of that move if this string was 'you have found sunken treasure chest!'then all the sonar devices on the board should be updated to detect the next closest treasure chest on the board the xy coordinates of all the sonar devices are in previousmoves by iterating over previousmoves on line you can pass all of these xy coordinates to the makemove(function again to redraw the values on the board because the program doesn' print anything new herethe player doesn' realize the program is redoing all of the previous moves it just appears that the board updates itself checking if the player has won if len(thechests= print('you have found all the sunken treasure chestscongratulations and good game!' break remember that the makemove(function modifies the thechests list you sent it because thechests is listany changes made to it inside the function will persist after execution returns from the function makemove(removes items from thechests when treasure chests are foundso eventually (if the player keeps guessing correctlyall of the treasure chests will have been removed rememberby "treasure chestwe mean the two-item lists of the xy coordinates inside the thechests list when all the treasure chests have been found on the board and removed from thecheststhe thechests list will have length of when that happensdisplay congratulations to the playerand then execute break statement to break out of this while loop execution will then move to line the first line after the while-block post questions to |
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 can re-evaluate the while statement' condition (which is sonardevices if sonardevices is then the condition will be false and execution will continue outside the while-block on line but until thenthe condition will remain true and the player can keep making guesses 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 here:' for xy in thechests print(% % (xy)line is the first line outside the while loop when the execution reaches this point the game is over if sonardevices is you know the player ran out of sonar devices before finding all the chests and lost lines to will tell the player they've lost the for loop on line will go through the treasure chests remaining in thechests and show their location to the player so that they can know where the treasure chests had been lurking the sys exit(function if not playagain()sys exit(win or loseplayagain(is called again to let the player type in whether they want to keep playing or not if notthen playagain(returns false the not operator on line changes this to truemaking the if statement' condition true and the sys exit(function is executed this will cause the program to terminate otherwiseexecution jumps back to the beginning of the while loop on line and new game begins |
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 when our game needs to find the distance between two points on the board locations in games that use cartesian coordinate system can be stored in list of lists so that the first index is the -coordinate and the second index is the -coordinate this make accessing coordinates look like board[ ][ythese data structures (such as the ones used for the ocean and locations of the treasure chestsmake it possible to have complicated concepts represented as dataand your game programs become mostly about modifying these data structures in the next we will be representing letters as numbers using their ascii numbers (this is the same ascii term we used in "ascii artpreviously by representing text as numberswe can perform math operations on them which will encrypt or decrypt secret messages post questions to |
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' really gamebut it is fun program the program will convert normal english into secret code it can also convert secret codes back into regular english again only someone who is knowledgeable about secret codes will be able to understand our secret messages because this program manipulates text to convert it into secret messagesyou will learn several new functions and methods for manipulating strings you will also learn how programs can do math with text strings just as it can with numbers cryptography the science of writing secret codes is called cryptography for thousands of years cryptography has made secret messages that only the sender and recipient could readeven if someone captured the messenger and read the coded message secret code system is called cipher the cipher used by the program in this is called the caesar cipher in cryptographywe call the message that we want to be secret the plaintext the plaintext could look like thishello therethe keys to the house are hidden under the flower pot converting the plaintext into the encoded message is called encrypting the plaintext the plaintext is encrypted into the ciphertext the ciphertext looks like random lettersand we cannot |
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 is the opposite of encryption many ciphers also use keys keys are secret values that let you decrypt ciphertext that was encrypted using specific cipher think of the cipher as being like door lock you can only unlock it with particular key if you are interested in writing cryptography programsyou can read my other book"hacking secret ciphers with pythonit is free to download from the caesar cipher the key for the caesar cipher will be number from to unless you know the key (that isknow the number used to encrypt the message)you won' be able to decrypt the secret code the caesar cipher was one of the earliest ciphers ever invented in this cipheryou encrypt message by taking each letter in the message (in cryptographythese letters are called symbols because they can be lettersnumbersor any other signand replacing it with "shiftedletter if you shift the letter by one spaceyou get the letter if you shift the letter by two spacesyou get the letter figure - is picture of some letters shifted over by three spaces figure - shifting over letters by three spaces hereb becomes to get each shifted letterdraw out row of boxes with each letter of the alphabet then draw second row of boxes under itbut start certain number (this number is the keyof spaces over after the letters at the endwrap around back to the start of the boxes here is an example with the letters shifted by three spacespost questions to |
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 letter "ybecomes "bthe ciphertext of "hellowith key becomes "krzgbwe will keep any non-letter characters the same to decrypt "krzgbwith the key we go from the bottom boxes back to the topthe letter "kbecomes "hthe letter "rbecomes "othe letter "zbecomes "wthe letter "gbecomes "dthe letter "bbecomes "yasciiand using numbers for letters how do we implement this shifting of the letters as codewe can do this by representing each letter as number called an ordinaland then adding or subtracting from this number to form new ordinal (and new letterascii (pronounced "ask-eeand stands for american standard code for information interchangeis code that connects each character to number between and |
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 with asciiso the utf- ordinals for ascii characters are the same as ascii' ordinals (space table - the ascii table so if you wanted to shift "aby three spacesyou would do the followingconvert "ato an ordinal ( add to to get convert the ordinal back to letter (" "the chr(and ord(functions can convert between characters and ordinals the chr(and ord(functions the chr(function (pronounced "char"short for "character"takes an integer ordinal and returns single-character string the ord(function (short for "ordinal"takes single-character stringand returns the integer ordinal value try entering the following into the interactive shellchr( 'apost questions to |
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 caesar cipher here is sample run of the caesar cipher programencrypting messagedo you wish to encrypt or decrypt messageencrypt enter your messagethe sky above the port was the color of televisiontuned to dead channel enter the key number ( - your translated text isgur fxl nobir gur cbeg jnf gur pbybe bs gryrivfvbagharq gb qrnq punaary now run the program and decrypt the text that you just encrypted do you wish to encrypt or decrypt messagedecrypt enter your messagegur fxl nobir gur cbeg jnf gur pbybe bs gryrivfvbagharq gb qrnq punaary enter the key number ( - your translated text isthe sky above the port was the color of televisiontuned to dead channel if you do not decrypt with the correct keythe decrypted text will be garbage datado you wish to encrypt or decrypt messagedecrypt enter your message |
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 cipher py if you get errors after typing this code incompare the code you typed to the book' code with the online diff tool at caesar py caesar cipher max_key_size def getmode() while true print('do you wish to encrypt or decrypt message?' mode input(lower( if mode in 'encrypt decrypt dsplit() return mode else print('enter either "encryptor "eor "decryptor " ' def getmessage() print('enter your message:' return input( def getkey() key while true print('enter the key number ( -% )(max_key_size) key int(input() if (key > and key <max_key_size) return key def gettranslatedmessage(modemessagekey) if mode[ =' ' key -key translated ' for symbol in message if symbol isalpha()post questions to |
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(gettranslatedmessage(modemessagekey)how the code works the encryption and decryption processes are the reverse of the otherand even then they still share much of the same code let' look at how each line works caesar cipher max_key_size the first line is just comment max_key_size is constant that stores the integer in it max_key_size reminds us that in this programthe key used in the cipher should be between and deciding to encrypt or decrypt def getmode() while true print('do you wish to encrypt or decrypt message?' |
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 the string stored in mode exists in the list returned by 'encrypt decrypt dsplit(this list is ['encrypt'' ''decrypt'' ']but it is easier for the programmer to type 'encrypt decrypt dsplit(and not type in all those quotes and commas use whichever is easiest for youthey both evaluate to the same list value this function will return the string in mode as long as mode is equal to 'encrypt'' ''decrypt'or 'dthereforegetmode(will return the string 'eor the string ' (but the user can type in either " ""encrypt"" "or "decryptgetting the message from the player def getmessage() print('enter your message:' return input(the getmessage(function simply gets the message to encrypt or decrypt from the user and returns it getting the key from the player def getkey() key while true print('enter the key number ( -% )(max_key_size) key int(input() if (key > and key <max_key_size) return key the getkey(function lets the player type in the key they will use to encrypt or decrypt the message the while loop ensures that the function keeps looping until the user enters valid key post questions to |
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 gettranslatedmessage(modemessagekey) if mode[ =' ' key -key translated 'gettranslatedmessage(does the encrypting and decrypting it has three parametersmode sets the function to encryption mode or decryption mode message is the plaintext (or ciphertextto be encrypted (or decryptedkey is the key that is used in this cipher line checks if the first letter in the mode variable is the string 'dif sothen the program is in decryption mode the only difference between the decryption and encryption mode is that in decryption mode the key is set to the negative version of itself if key was the integer then in decryption mode set it to - the reason why will be explained later translated is the string of the resulteither the ciphertext (if you are encryptingor the plaintext (if you are decryptingit starts as the blank string and has encrypted or decrypted characters concatenated to the end of it the isalpha(string method the isalpha(string method will return true if the string is an uppercase or lowercase letter from to if the string contains any non-letter charactersthen isalpha(will return false try entering the following into the interactive shell'helloisalpha(true 'forty twoisalpha(false 'fortytwoisalpha(true ' isalpha(false 'isalpha(false |
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 isn' blank the isalpha(method is used in the next few lines of the program for symbol in messageif symbol isalpha()num ord(symbolnum +key line ' for loop iterates over each letter (in cryptography they are called symbolsin the message string on each iteration through this loopsymbol will have the value of letter in message line is there because only letters will be encrypted or decrypted numberspunctuation marksand everything else will stay in their original form the num variable will hold the integer ordinal value of the letter stored in symbol line then "shiftsthe value in num by the value in key the isupper(and islower(string methods the isupper(and islower(string methods (which are on line and work in way that is similar to the isdigit(and isalpha(methods isupper(will return true if the string it is called on contains at least one uppercase letter and no lowercase letters islower(returns true if the string it is called on contains at least one lowercase letter and no uppercase letters otherwise these methods return false try entering the following into the interactive shell'helloisupper(true 'helloisupper(false 'helloislower(true 'helloislower(false 'look out behind you!isupper(true ' isupper(false post questions to |
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 would be the character '^(the ordinal of '^is but isn' letter at all you want the ciphertext to "wrap aroundto the beginning of the alphabet check if num has value larger than the ordinal value for "zif sothen subtract (because there are letters in totalfrom num after doing thisthe value of num is is the correct ordinal value for ' elif symbol islower()if num ord(' ')num - elif num ord(' ')num + if the symbol is lowercase letterthe program runs code that is similar to lines through the only difference is that it uses ord(' 'and ord(' 'instead of ord(' 'and ord(' 'in decrypting modethen key would be negative the special case would be where num - is less than the ascii value for "ain that caseadd to num to have it "wrap aroundto the end of the alphabet translated +chr(numelsetranslated +symbol line concatenates the encrypted/decrypted character to the translated string |
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 start of the program mode getmode( message getmessage( key getkey( print('your translated text is:' print(gettranslatedmessage(modemessagekey)the start of the program calls each of the three functions defined previously to get the modemessageand key from the user these three values are passed to gettranslatedmessage(whose return value (the translated stringis printed to the user brute force that' the entire caesar cipher howeverwhile this cipher may fool some people who don' understand cryptographyit won' keep message secret from someone who knows cryptanalysis while cryptography is the science of making codescryptanalysis is the science of breaking codes do you wish to encrypt or decrypt messageencrypt enter your messagedoubts may not be pleasantbut certainty is absurd enter the key number ( - your translated text islwcjba uig vwb jm xtmiaivbjcb kmzbiqvbg qa ijaczl the whole point of cryptography is that so if someone else gets their hands on the encrypted messagethey cannot figure out the original unencrypted message from it let' pretend we are the code breaker and all we have is the encrypted textlwcjba uig vwb jm xtmiaivbjcb kmzbiqvbg qa ijaczl post questions to |
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 the program adding the brute force mode firstchange lines and (which are in the getmode(functionto look like the following (the changes are in bold) def getmode() while true print('do you wish to encrypt or decrypt or brute force message?' mode input(lower( if mode in 'encrypt decrypt brute bsplit() return mode[ else print('enter either "encryptor "eor "decryptor "dor "bruteor " 'this code will let the user select "brute forceas mode modify and add the following changes to the main part of the program mode getmode( message getmessage( if mode[ !' ' key getkey( print('your translated text is:' if mode[ !' ' print(gettranslatedmessage(modemessagekey) else for key in range( max_key_size ) print(keygettranslatedmessage('decrypt'messagekey)these changes ask the user for key if they are not in "brute forcemode the original gettranslatedmessage(call is made and the translated string is printed howeverif the user is in "brute forcemode then gettranslatedmessage(loop that iterates from all the way up to max_key_size (which is remember that when the range(function returns list of integers up tobut not includingthe second parameterwhich is why you have |
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 thf uva il wslhzhuaiba jlyahpuaf pz hizbyk juahzy sge tuz hk vrkgygtzhaz ikxzgotze oy ghyaxj itzgyx rfd sty gj uqjfxfsygzy hjwyfnsyd nx fgxzwi hsyfxw qec rsx fi tpiewerxfyx givxemrxc mw efwyvh grxewv pdb qrw eh sohdvdqwexw fhuwdlqwb lv devxug fqwdvu oca pqv dg rngcucpvdwv egtvckpva ku cduwtf epvcut nbz opu cf qmfbtboucvu dfsubjouz jt bctvse doubts may not be pleasantbut certainty is absurd cntasr lzx mns ad okdzrzmsats bdqszhmsx hr zartqc bmszrq kyw lmr zc njcyqylrzsr acpryglrw gq yzqspb alryqp jxv klq yb mibxpxkqyrq zboqxfkqv fp xyproa zkqxpo iwu jkp xa lhawowjpxqp yanpwejpu eo wxoqnz yjpwon hvt ijo wz kgzvnviowpo xzmovdiot dn vwnpmy xiovnm gus hin vy jfyumuhnvon wylnuchns cm uvmolx whnuml ftr ghm ux iextltgmunm vxkmtbgmr bl tulnkw vgmtlk esq fgl tw hdwsksfltml uwjlsaflq ak stkmjv uflskj drp efk sv gcvrjrekslk tvikrzekp zj rsjliu tekrji cqo dej ru fbuqiqdjrkj suhjqydjo yi qrikht sdjqih bpn cdi qt eatphpciqji rtgipxcin xh pqhjgs rciphg aom bch ps dzsogobhpih qsfhowbhm wg opgifr qbhogf znl abg or cyrnfnagohg pregnvagl vf nofheq pagnfe ymk zaf nq bxqmemzfngf oqdfmuzfk ue mnegdp ozfmed xlj yze mp awpldlyemfe npceltyej td lmdfco nyeldc wki xyd lo zvokckxdled mobdksxdi sc klcebn mxdkcb vjh wxc kn yunjbjwckdc lnacjrwch rb jkbdam lwcjba uig vwb jm xtmiaivbjcb kmzbiqvbg qa ijaczl after looking over each rowyou can see that the th message isn' garbagebut plain englishthe cryptanalyst can deduce that the original key for this encrypted text must have been this brute force would have been difficult to do back in the days of caesars and the roman empirebut today we have computers that can quickly go through millions or even billions of keys in short time post questions to |
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 messages that will keep them secret from people who have to figure it out with pencil and paperit won' keep it secret from people who know how to get computers to process information for them (our brute force mode proves this large part of figuring out how to write program is figuring out how to represent the information you want to manipulate as values that python can understand the next will present reversi (also known as othellothe ai that plays this game will be much more advanced than the ai that played tic tac toe in in factthe ai is so good most of the time you'll be unable to beat it |
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 is more advanced than the ai we made for tic tac toe in factthis ai is so good that it will probably beat you almost every time you play ( know lose whenever play against it!reversi has an board and tiles that are black on one side and white on the other (our game will use ' and ' insteadthe starting board looks like figure - the black player and white player take turns placing down new tile of their color any of the opponent' tiles that are between the new tile and the other tiles of that color are flipped the goal of the game is to have as many of the tiles with your color as possible for examplefigure - is what it looks like if the white player places new white tile on space figure - the starting reversi board has two white tiles and two black tiles post questions to figure - white places new tile |
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' move will flip over one of black' tiles figure - black places new tilewhich flips over one of white' tiles tiles in all directions are flipped as long as they are between the player' new tile and existing tile in figure - the white player places tile at and flips black tiles in both directions (marked by the lines the result is in figure - figure - white' second move at will flip two of black' tiles figure - the board after white' second move |
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 corner moves they can take if there are no corner moves availablethen the computer will select the move that claims the most tiles sample run of reversi welcome to reversido you want to be or ox the player will go first +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- post questions to |
7,669 | +---+---+---+---+---+---+---+---you have points the computer has points enter your moveor type quit to end the gameor hints to turn off/on hints +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+---you have points the computer has points press enter to see the computer' move skipped for brevity +---+---+---+---+---+---+---+--- |
7,670 | +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+---you have points the computer has points enter your moveor type quit to end the gameor hints to turn off/on hints scored points scored points you lost the computer beat you by points do you want to play again(yes or nono as you can seethe ai was pretty good at beating me to to help the player outwe'll program the game to provide hints if the player types 'hintsas their movethey can toggle the hints mode on and off when hints mode is onall the possible moves the player can make will show up on the board as characterslike thispost questions to |
7,671 | +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+---source code of reversi reversi is mammoth program compared to our previous games it' over lines longbut don' worrymany of these lines are comments or blank lines to space out the code and make it more readable as with our other programswe'll first create several functions to carry out reversi-related tasks that the main section will call roughly the first lines of code are for these helper functionsand the last lines of code implement the reversi game itself |
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 for in range( ) print(vline print( + end=' for in range( ) print('% (board[ ][ ])end=' print('|' print(vline print(hline def resetboard(board) blanks out the board it is passedexcept for the original starting position for in range( ) for in range( ) board[ ][ starting pieces board[ ][ ' board[ ][ ' board[ ][ ' board[ ][ ' def getnewboard() creates brand newblank board data structure board [ for in range( ) board append([' post questions to |
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 set the tile on the board if tile =' ' othertile ' else othertile ' tilestoflip [ for xdirectionydirection in [[ ][ ][ ][ - ][ ][- - ][- ][- ]] xy xstartystart +xdirection first step in the direction +ydirection first step in the direction if isonboard(xyand board[ ][ =othertile there is piece belonging to the other player next to our piece +xdirection +ydirection if not isonboard(xy) continue while board[ ][ =othertile +xdirection +ydirection if not isonboard(xy)break out of while loopthen continue in for loop break if not isonboard(xy) continue if board[ ][ =tile there are pieces to flip over go in the reverse direction until we reach the original spacenoting all the tiles along the way while true -xdirection -ydirection if =xstart and =ystart |
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 board with marking the valid moves the given player can make dupeboard getboardcopy(board for xy in getvalidmoves(dupeboardtile) dupeboard[ ][ return dupeboard def getvalidmoves(boardtile) returns list of [ ,ylists of valid moves for the given player on the given board validmoves [ for in range( ) for in range( ) if isvalidmove(boardtilexy!false validmoves append([xy] return validmoves def getscoreofboard(board) determine the score by counting the tiles returns dictionary with keys 'xand ' xscore oscore for in range( ) for in range( ) if board[ ][ =' ' xscore + if board[ ][ =' 'post questions to |
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 the player' tilethe second is the computer' tile if tile =' ' return [' '' ' else return [' '' ' def whogoesfirst() randomly choose the player who goes first if random randint( = return 'computer else return 'player def playagain() this function returns true if the player wants to play againotherwise it returns false print('do you want to play again(yes or no)' return input(lower(startswith(' ' def makemove(boardtilexstartystart) place the tile on the board at xstartystartand flip any of the opponent' pieces returns false if this is an invalid movetrue if it is valid tilestoflip isvalidmove(boardtilexstartystart if tilestoflip =false return false board[xstart][ystarttile for xy in tilestoflip |
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 ( = and = or ( = and = def getplayermove(boardplayertile) let the player type in their move returns the move as [xy(or returns the strings 'hintsor 'quit' digits to ' split( while true print('enter your moveor type quit to end the gameor hints to turn off/on hints ' move input(lower( if move ='quit' return 'quit if move ='hints' return 'hints if len(move= and move[ in digits to and move[ in digits to int(move[ ] int(move[ ] if isvalidmove(boardplayertilexy=false continue else break else print('that is not valid move type the digit ( - )then the digit ( - ' print('for example will be the top-right corner 'post questions to |
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 isoncorner(xy) return [xy go through all the possible moves and remember the best scoring move bestscore - for xy in possiblemoves dupeboard getboardcopy(board makemove(dupeboardcomputertilexy score getscoreofboard(dupeboard)[computertile if score bestscore bestmove [xy bestscore score return bestmove def showpoints(playertilecomputertile) prints out the current score scores getscoreofboard(mainboard print('you have % points the computer has % points (scores[playertile]scores[computertile]) print('welcome to reversi!' while true reset the board and game mainboard getnewboard( resetboard(mainboard playertilecomputertile enterplayertile( showhints false turn whogoesfirst( print('the turn will go first ' |
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 move ='hints' showhints not showhints continue else makemove(mainboardplayertilemove[ ]move[ ] if getvalidmoves(mainboardcomputertile=[] break else turn 'computer else computer' turn drawboard(mainboard showpoints(playertilecomputertile input('press enter to see the computer\' move ' xy getcomputermove(mainboardcomputertile makemove(mainboardcomputertilexy if getvalidmoves(mainboardplayertile=[] break else turn 'player display the final score drawboard(mainboard scores getscoreofboard(mainboard print(' scored % points scored % points (scores[' ']scores[' ']) if scores[playertilescores[computertile] print('you beat the computer by % pointscongratulations!(scores[playertilescores[computertile])post questions to |
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 structure is list of listsjust like the one in the previous sonar game the list of lists is created so that board[ ][ywill represent the character on space located at position on the -axis (going left/rightand position on the -axis (going up/downthis character can either be space character (to represent blank space) period character (to represent possible move in hint mode)or an 'xor ' (to represent player' tilewhenever you see parameter named boardit is meant to be this kind of list of lists data structure importing other modules reversi import random import sys line imports the random module for its randint(and choice(functions line imports the sys module for its exit(function drawing the board data structure on the screen def drawboard(board) this function prints out the board that it was passed returns none hline +---+---+---+---+---+---+---+---+ vline | print( ' print(hline |
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 will save you from typing out the string repeatedly there are also lines above and below the center of tile that are nothing but '|characters (called "pipecharacterswith three spaces between this is stored in constant named vline line is the first print(function call executedand it prints the labels for the -axis along the top of the board line prints the top horizontal line of the board for in range( )print(vlineprint( + end='for in range( )print('% (board[ ][ ])end='print('|'print(vlineprint(hlinethe for loop will loop eight timesonce for each row line prints the label for the -axis on the left side of the boardand has an end=keyword argument to print single space instead of new line this is so that another loop (which again loops eight timesonce for each spaceprints each space (along with the ' '' 'or character depending on what is stored in board[ ][ythe print(function call inside the inner loop also has an end=keyword argument at the end of itmeaning space character is printed instead of newline character that will produce single line on the screen that looks like ' (if each of the board[ ][yvalues were ' 'after the inner loop is donethe print(function call on line prints the final '|character along with newline the code inside the outer for loop from line to line prints an entire row of the board like thispost questions to |
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 ' ') +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+--- +---+---+---+---+---+---+---+---resetting the game board def resetboard(board) blanks out the board it is passedexcept for the original starting position |
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 the beginning of gameeach player has two tiles already laid down in the center lines to set those tiles on the blank board the resetboard(function does not have to return the board variablebecause board is reference to list making changes inside the function' local scope will modify the original list that was passed as the argument (see the references section in creating new game board data structure def getnewboard() creates brand newblank board data structure board [ for in range( ) board append([' return board the getnewboard(function creates new board data structure and returns it line creates the outer list and stores reference to this list in board line creates the inner lists using list replication ([' evaluates to be the same as [''''''''but with less typing line ' for loop here creates the eight inner lists the spaces represent completely empty game board what board ends up being is list of eight listsand each of those eight lists themselves has eight strings the result is strings post questions to |
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 temporarily set the tile on the board if tile =' ' othertile ' else othertile ' tilestoflip [given board data structurethe player' tileand the xy coordinates for player' moveisvalidmove(should return true if the reversi game rules allow move to those coordinates and false if they don' line checks if the xy coordinates are not on the game boardor if the space isn' empty isonboard(is function defined later in the program that makes sure both the and coordinates are between and the next step is to temporarily place the player' tile on the board this tile will be removed (by setting the board space back to before returningthe player' tile (either the human player or the computer playeris in tilebut this function will need to know the other player' tile if the player' tile is 'xthen obviously the other player' tile is ' 'and vice versa finallyif the given xy coordinate ends up as valid positionisvalidmove(returns list of all the opponent' tiles that would be flipped by this move for xdirectionydirection in [[ ][ ][ ][ - ][ ][- - ][- ][- ]]the for loop iterates through list of lists which represent directions you can move on the game board the game board is cartesian coordinate system with an and direction there are eight directions you can moveupdownleftrightand the four diagonal directions each of the eight -item lists in the list on line is used for moving in one of these directions the program moves in direction by adding the first value in the two-item list to the coordinateand the second value to the coordinate |
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 to add or subtract to both coordinates for exampleadding to the coordinate to move right and adding - to the coordinate to move up would result in moving to the up-right diagonal direction checking each of the eight directions here is diagram to make it easier to remember which two-item list represents which directionfigure - each two-item list represents one of the eight directions for xdirectionydirection in [[ ][ ][ ][ - ][ ][- - ][- ][- ]] xy xstartystart +xdirection first step in the direction +ydirection first step in the direction line sets an and variable to be the same value as xstart and ystartrespectivelyusing multiple assignment change and to "movein the direction that xdirection and ydirection dictate the xstart and ystart variables will stay the same so that the program can remember which space it originally started from post questions to |
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' any of the opponent' tiles to flipand valid move must flip over at least one tile if these two things aren' trueline ' condition isn' true and the execution goes back to the for statement for the next direction but if the first space does have the other player' tilethen the program should keep checking in that direction until it reaches one of the player' tiles if it reaches past the end of the board thoughthen line should continue back to the for statement to try the next direction while board[ ][ =othertile +xdirection +ydirection if not isonboard(xy)break out of while loopthen continue in for loop break if not isonboard(xy) continue the while loop on line keeps looping so that and keep going in the current direction as long as it keeps seeing trail of the other player' tiles if line detects that and moved off of the boardline breaks out of the for loop and the flow of execution moves to line what you really want to do is break out of the while loop but continue in the for loop this is why line rechecks not isonboard(xyand runs continuewhich moves execution to the next direction in line ' for statement rememberbreak and continue statements will only break or continue from the innermost loop they are in finding out if there are pieces to flip over if board[ ][ =tile there are pieces to flip over go in the reverse direction until we reach the original spacenoting all the tiles along the way while true |
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 reverse back to the original xstart and ystart position by subtracting and each space is appended to the tilestoflip list board[xstart][ystartrestore the empty space if len(tilestoflip= if no tiles were flippedthis is not valid move return false return tilestoflip the for loop that started on line does this in all eight directions after that loop is donethe tilestoflip list will contain the xy coordinates all of our opponent' tiles that would be flipped if the player moved on xstartystart rememberthe isvalidmove(function is only checking to see if the original move was valid it doesn' actually permanently change the data structure of the game board if none of the eight directions ended up flipping at least one of the opponent' tilesthen tilestoflip will be an empty list this is sign that this move is not valid and isvalidmove(should return false otherwiseisvalidmove(returns tilestoflip checking for valid coordinates def isonboard(xy) returns true if the coordinates are located on the board return > and and <= isonboard(is function called from isvalidmove(calling the function is shorthand for the boolean expression on line that is true if both and are between and this function post questions to |
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 getboardcopy(board for xy in getvalidmoves(dupeboardtile) dupeboard[ ][ return dupeboard getboardwithvalidmoves(returns game board data structure that has characters for all spaces that are valid moves the periods are for the hints mode that displays board with all possible moves marked on it this function creates duplicate game board data structure (returned by getboardcopy(on line instead of modifying the one passed to it in the board parameter line calls getvalidmoves(to get list of xy coordinates with all the legal moves the player could make the board copy is marked with periods in those spaces and returned def getvalidmoves(boardtile) returns list of [ ,ylists of valid moves for the given player on the given board validmoves [ for in range( ) for in range( ) if isvalidmove(boardtilexy!false validmoves append([xy] return validmoves the getvalidmoves(function returns list of two-item lists these lists hold the xy coordinates for all valid moves for tile' player for the board data structure in the board parameter this function uses nested loops (on lines and to check every xy coordinate (all sixty four of themby calling isvalidmove(on that space and checking if it returns false or list of possible moves (in which case it is valid moveeach valid xy coordinate is appended to the list in validmoves |
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 empty listand the empty dictionary are all considered to be false when used as the condition for an if or loop statement all other values are true try entering the following into the interactive shellbool( false bool( false bool(''false bool([]false bool({}false bool( true bool('hello'true bool([ ]true bool({'spam':'cheese''fizz':'buzz'}true imagine that any statement' condition is placed inside call to bool(that isconditions are automatically interpreted as boolean values this is why the condition on line works correctly the call to the isvalidmove(function either returns the boolean value false or non-empty list if you imagine that the entire condition is placed inside call to bool()then line ' condition false becomes bool(false(whichof courseevaluates to falseand condition of nonempty list placed as the parameter to bool(will return true getting the score of the game board def getscoreofboard(board) determine the score by counting the tiles returns dictionary with keys 'xand ' xscore post questions to |
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 line for each 'otilethe code increments oscore on line getting the player' tile choice 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(this function asks the player which tile they want to beeither 'xor 'othe for loop will keep looping until the player types in 'xor ' the first element in the list is the player' tilethe second is the computer' tile if tile =' ' return [' '' ' else return [' '' 'the enterplayertile(function then returns two-item listwhere the player' tile choice is the first item and the computer' tile is the second line which calls enterplayertile()uses multiple assignment to put these two returned items in two variables determining who goes first def whogoesfirst() randomly choose the player who goes first |
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 want to play again(yes or no)' return input(lower(startswith(' 'the playagain(function was also in previous games if the player types in string that begins with ' 'then the function returns true otherwise the function returns false placing down tile on the game board def makemove(boardtilexstartystart) place the tile on the board at xstartystartand flip any of the opponent' pieces returns false if this is an invalid movetrue if it is valid tilestoflip isvalidmove(boardtilexstartystartmakemove(is called when you want to place tile on the board and flip the other tiles according to the rules of reversi this function modifies the board data structure that is passed in-place changes made to the board variable (because it is list referencewill be made to the global scope most of the work is done by isvalidmove()which returns list of xy coordinates (in twoitem listof tiles that need to be flipped (rememberif the xstart and ystart arguments point to an invalid movethen isvalidmove(will return the boolean value false if tilestoflip =falsereturn false board[xstart][ystarttile for xy in tilestoflipboard[ ][ytile post questions to |
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 that are in tilestoflip copying the board data structure 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 getboardcopy(is different from getnewboard(getnewboad(will create blank game board data structure which has only empty spaces and the four starting tiles getboardcopy(will create blank game board data structurebut then copy all of the spaces from the board parameter this function is used by the ai to have game board that it can change around without changing the real game board this technique was also used by the previous tic tac toe program call to getnewboard(handles getting fresh game board data structure then the two nested for loops copy each of the tiles from board to the duplicate board data structure in dupeboard determining if space is on corner def isoncorner(xy) returns true if the position is in one of the four corners return ( = and = or ( = and = or ( = and = or ( = and = the isoncorner(function returns true if the coordinates are on corner space at coordinates ( , )( , )( , or ( , otherwise isoncorner(returns false |
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 also type in 'hintsto turn hints mode on (if it is offor off (if it is onthe player can also type in 'quitto quit the game the digits to constant variable is the list [' '' '' '' '' '' '' '' 'the digits to constant is used because it is easier to type than the entire list you can' use the isdigit(method because that would allow and to be enteredwhich are not valid coordinates on the board while true print('enter your moveor type quit to end the gameor hints to turn off/on hints ' move input(lower( if move ='quit' return 'quit if move ='hints' return 'hintsthe while loop will keep looping until the player has typed in valid move lines to check if the player wants to quit or toggle hints modeand return the string 'quitor 'hints'respectively the lower(method is called on the string returned by input(so the player can type 'hintsor 'quitbut still have the command understood the code that called getplayermove(will handle what to do if the player wants to quit or toggle hints mode digits to if len(move= and move[ in digits to and move[ in int(move[ ] int(move[ ] if isvalidmove(boardplayertilexy=falsecontinue elsebreak post questions to |
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 stringare strings that exist in digits to remember that the game board data structures have indexes from to not to the code prints to when the board is displayed in drawboard(because non-programmers are used to numbers beginning at instead of so to convert the strings in move[ and move[ to integerslines and subtract even if the player typed in correct movethe code still needs to check that the move is allowed by the rules of reversi this is done by isvalidmove(which is passed the game board data structurethe player' tileand the xy coordinates of the move if isvalidmove(returns falsethen line ' continue statement executes the execution will then go back to the beginning of the while loop and asks the player for valid move again otherwisethe player did type in valid move and the execution needs to break out of the while loop else print('that is not valid move type the digit ( - )then the digit ( - ' print('for example will be the top-right corner 'if the if statement' condition on line was falsethen the player didn' type in valid move lines and instructs them on how to correctly type in moves afterwardsthe execution moves back to the while statement on line because line isn' only the last line in the elseblockbut also the last line in the while-block return [xyfinallygetplayermove(returns two-item list with the xy coordinates of the player' valid move getting the computer' move def getcomputermove(boardcomputertile) given board and the computer' tiledetermine where to move and return that move as [xylist possiblemoves getvalidmoves(boardcomputertile |
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 also find all the possible moves that the computer can make the ai will select the best move from this list randomize the order of the possible moves random shuffle(possiblemovesfirstrandom shuffle(will randomize the order of moves in the possiblemoves list why we want to shuffle the possiblemoves list will be explained laterbut first let' look at the algorithm corner moves are the best moves always go for corner if available for xy in possiblemovesif isoncorner(xy)return [xyfirstline loops through every move in possiblemoves if any of them are on the cornerreturn that space is returned as the move corner moves are good idea in reversi because once tile has been placed on the cornerit can never be flipped over since possiblemoves is list of two-item listsuse multiple assignment in the for loop to set and if possiblemoves contains multiple corner movesthe first one is always used but since possiblemoves was shuffled on line it is random which corner move is first in the list get list of the best scoring moves go through all the possible moves and remember the best scoring move bestscore - for xy in possiblemovesdupeboard getboardcopy(boardmakemove(dupeboardcomputertilexyscore getscoreofboard(dupeboard)[computertileif score bestscorebestmove [xybestscore score return bestmove if there are no corner movesloop through the entire list and find out which move results in the highest score line ' for loop will set and to every move in possiblemoves bestmove is post questions to |
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 before simulating moveline makes duplicate game board data structure by calling getboardcopy(you'll want copy so you can modify without changing the real game board data structure stored in the board variable then line calls makemove()passing the duplicate board (stored in dupeboardinstead of the real board this will simulate what would happen on the real board if this move was made makemove(will handle placing the computer' tile and the flipping the player' tiles on the duplicate board line calls getscoreofboard()with the duplicate boardwhich returns dictionary where the keys are 'xand ' 'and the values are the scores for examplepretend that getscoreofboard(returns the dictionary {' ': ' ': and computertile is 'xthen getscoreofboard(dupeboard)[computertilewould evaluate to {' ': ' ': }[' ']which would then evaluate to if is larger than bestscorebestscore is set to and bestmove is set to the current and values by the time this for loop is finishedyou can be sure that bestscore is the highest possible score move can makeand that move is stored in bestmove line first sets bestscore to - so that the first move the code checks will be set to the first bestmove this will guarantee that bestmove is set to one of the moves from possiblemoves when it returns even though the code always chooses the first in the list of these tied movesit' random because the list order was shuffled on line this ensures that the ai won' be predictable when there' more than one best move printing the scores to the screen def showpoints(playertilecomputertile) prints out the current score scores getscoreofboard(mainboard print('you have % points the computer has % points (scores[playertile]scores[computertile]) |
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 calls these functions as needed the start of the game print('welcome to reversi!' while true reset the board and game mainboard getnewboard( resetboard(mainboard playertilecomputertile enterplayertile( showhints false turn whogoesfirst( print('the turn will go first 'the while loop on line is the main game loop the program will loop back to line when new game starts first get new game board data structure by calling getnewboard(and set the starting tiles by calling resetboard(mainboard is the main game board data structure for the program the call to enterplayertile(will let the player type in whether they want to be 'xor 'othe return value is then stored in playertile and computertile using multiple assignment showhints is boolean value that determines if hints mode is on or off it starts as off as false on line the turn variable is string that either has the string value 'playeror 'computerit will keep track of whose turn it is it is set to the return value of whogoesfirst()which randomly chooses who will go first running the player' turn while true if turn ='player' player' turn if showhints validmovesboard getboardwithvalidmoves(mainboardplayertile drawboard(validmovesboard elsepost questions to |
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-block that starts on line has the code for the computer' turn first the board is displayed on the screen if hints mode is on (that isshowhints is true)then the board data structure needs to have period characters on every valid space the player could move the getboardwithvalidmoves(function does that it is passed game board data structure and returns copy that also contains period characters line passes this board to the drawboard(function if hints mode is offthen line passes mainboard to drawboard(after printing out the game board to the playeryou also want to print the current score by calling showpoints(on line move getplayermove(mainboardplayertilenextlet the player type in their move getplayermove(handles thisand its return value is two-item list of the xy coordinate of the player' move getplayermove(has already made sure that the move the player typed in is valid move handling the quit or hints commands if move ='quit'print('thanks for playing!'sys exit(terminate the program elif move ='hints'showhints not showhints continue elsemakemove(mainboardplayertilemove[ ]move[ ]if the player typed in the string 'quitfor their movethen getplayermove(would have returned the string 'quitin that caseline calls the sys exit(to terminate the program |
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 evaluates to false then the continue statement moves the execution to the start of the loop (turn has not changedso it will still be the player' turnotherwiseif the player didn' quit or toggle hints modeline calls makemove(to make the player' move on the board make the player' move if getvalidmoves(mainboardcomputertile=[]break elseturn 'computerafter making the player' moveline calls getvalidmoves(to see if the computer could make any moves if getvalidmoves(returns blank listthen there are no more valid moves that the computer could make in that caseline breaks out of the while loop and ends the game otherwiseline sets turn to 'computerthe flow of execution skips the else-block and reaches the end of the while-blockso execution jumps back to the while statement on line this timehoweverit will be the computer' turn running the computer' turn elsecomputer' turn drawboard(mainboardshowpoints(playertilecomputertileinput('press enter to see the computer\' move 'xy getcomputermove(mainboardcomputertilemakemove(mainboardcomputertilexyafter printing out the board with drawboard()also print the current score with call to showpoints(on line line calls input(to pause the script while the player can look at the board this is much like how input(was used to pause the program in the jokes instead of using print(post questions to |
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 finallypass and yalong with the game board data structure and the computer' tileto the makemove(function this places the computer' tile on the game board in mainboard to reflect the computer' move line ' call to getcomputermove(got the computer' move (and stored it in variables and ythe call to makemove(on line makes the move on the board if getvalidmoves(mainboardplayertile=[]break elseturn 'playerlines to are similar to lines to after the computer has made its moveline checks if there exist any valid moves the human player can make if getvalidmoves(returns an empty listthen there are no valid moves that means the game is overand line breaks out of the while loop otherwisethere' at least one possible move the player should make the turn variable is to 'playerthere is no more code in the while-block after line so execution loops back to the while statement on line drawing everything on the screen display the final score drawboard(mainboard scores getscoreofboard(mainboard print(' scored % points scored % points (scores[' ']scores[' ']) if scores[playertilescores[computertile] print('you beat the computer by % pointscongratulations!(scores[playertilescores[computertile]) elif scores[playertilescores[computertile] print('you lost the computer beat you by % points (scores[computertilescores[playertile]) else print('the game was tie!' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.