MCPcopy Create free account
hub / github.com/asweigart/PythonStdioGames / askForPlayerMove

Function askForPlayerMove

src/gamesbyexample/towerofhanoi.py:46–78  ·  view source on GitHub ↗

Asks the player for a move. Returns (fromTower, toTower).

(towers)

Source from the content-addressed store, hash-verified

44
45
46def 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.&#x27;)
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
81def displayTowers(towers):

Callers 1

mainFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected