Asks the player for a move. Returns (fromTower, toTower).
(towers)
| 44 | |
| 45 | |
| 46 | def askForPlayerMove(towers): |
| 47 | """Asks the player for a move. Returns (fromTower, toTower).""" |
| 48 | |
| 49 | while True: # Keep asking player until they enter a valid move. |
| 50 | print('Enter the letters of "from" and "to" towers, or QUIT.') |
| 51 | print('(e.g. AB to moves a disk from tower A to tower B.)') |
| 52 | response = input('> ').upper().strip() |
| 53 | |
| 54 | if response == 'QUIT': |
| 55 | print('Thanks for playing!') |
| 56 | sys.exit() |
| 57 | |
| 58 | # Make sure the user entered valid tower letters: |
| 59 | if response not in ('AB', 'AC', 'BA', 'BC', 'CA', 'CB'): |
| 60 | print('Enter one of AB, AC, BA, BC, CA, or CB.') |
| 61 | continue # Ask player again for their move. |
| 62 | |
| 63 | # Syntactic sugar - Use more descriptive variable names: |
| 64 | fromTower, toTower = response[0], response[1] |
| 65 | |
| 66 | if len(towers[fromTower]) == 0: |
| 67 | # The "from" tower cannot be an empty tower: |
| 68 | print('You selected a tower with no disks.') |
| 69 | continue # Ask player again for their move. |
| 70 | elif len(towers[toTower]) == 0: |
| 71 | # Any disk can be moved onto an empty "to" tower: |
| 72 | return fromTower, toTower |
| 73 | elif towers[toTower][-1] < towers[fromTower][-1]: |
| 74 | print('Can\'t put larger disks on top of smaller ones.') |
| 75 | continue # Ask player again for their move. |
| 76 | else: |
| 77 | # This is a valid move, so return the selected towers: |
| 78 | return fromTower, toTower |
| 79 | |
| 80 | |
| 81 | def displayTowers(towers): |