Add a Command-Line Interface
Add a Command-Line Interface. You are almost done building your tic-tac-toe front end. However, it’s time to add the finishing touches and turn it into a playable game by implementing a useful command-line interface using the
That way, you’ll be able to choose the player types and the starting mark before running the game. The entry point to your console front end is the special
__main__.py module, which makes the containing package runnable through the
You import the game engine, your new console renderer, and a helper function,
parse_args(), which will be able to read the command-line arguments and, based on them, return two-player objects and the starting player’s mark.
To implement the passing of arguments, you can start by defining the available player types as a Python dictionary, which associates everyday names, such as human, with concrete classes extending the abstract
This will make it more straightforward to add more player types in the future. Next, you can write a function that will use the
argparse module to get the expected arguments from the command line.
This code translates to the three optional arguments seen on screen, all of which have default values. At this point, the function parses those arguments and stores their values as strings in a special
NameSpace object under the attributes named
03:47 But the function is expected to return a tuple consisting of custom data types instead of strings. To make the function’s body comply with its signature, you can map strings provided by the user to the respective classes using your dictionary.
04:09 You translate the user-supplied names to concrete player classes. If the starting player’s mark is different from the default one, then you swap the two players before returning them from the function.
05:53 Unfortunately, it isn’t particularly challenging to play against a computer making moves at random. So in the next chapter of the course, you’ll implement a more advanced computer player leveraging the minimax algorithm, making it practically undefeatable.
Become a Member to join the conversation.