22 Tic-Tac-Toe redux: An interactive version with type hints

 

In this last exercise, we’re going to revisit the Tic-Tac-Toe game from the previous chapter. That version played one turn of the game by accepting an initial --board and then modifying it if there were also valid options for --player and --cell. It printed the one board and the winner, if any. We’re going to extend those ideas into a version that will always start from an empty board and will play as many turns as needed to complete a game, ending with a winner or a draw.


This program will be different from all the other programs in this book because it will accept no command-line arguments. The game will always start with a blank “board” and with the X player going first. It will use the input() function to interactively ask each player, X and then O, for a move. Any invalid move, such as choosing an occupied or non-existing cell, will be rejected. At the end of each turn, the game will decide to stop if it determines there is a win or a draw.

In this chapter you will

  • Use and break out of an infinite loop
  • Add type hints to your code
  • Explore tuples, named tuples, and typed dictionaries
  • Use mypy to analyze code for errors, especially misuse of types

22.1 Writing itictactoe.py

 
 
 

22.1.1 Tuple talk

 
 

22.1.2 Named tuples

 
 
 
 

22.1.3 Adding type hints

 
 

22.1.4 Type verification with Mypy

 
 

22.1.5 Updating immutable structures

 
 
 
 

22.1.6 Adding type hints to function definitions

 
 
 

22.2 Solution

 

22.2.1 A version using TypedDict

 
 

22.2.2 Thinking about state

 
 

22.3 Going further

 
 
 

Summary

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage