Greetings and welcome to part 3 of the Python 3 basics tutorials. In this video we're going to begin to tackle an actual challenge: Creating a game of TicTacToe!
The game of TicTacToe, while simple for us to understand, has quite a few challenges for us to deal with while coding. Things like displaying the game's board, allowing players to input moves, updating the game board, detecting a winner, and so on. Beyond this, we also have to think about where things might go wrong, such as players attempting to play where someone else has already played, or playing in a non-existent spot, and so on!
As you may be realizing now, despite the simplicity of TicTacToe, there are many smaller intricacies that we have to deal with and handle for that we just take for given when we play on a piece of paper. With any task like these where there are many things to be done, we need to just break down the entire objective, either in our head or in some notes. In this case, we know we need some basic things:
We can tackle these in order, so let's start with #1. How will we visualize this board? I propose, to start, we just use lists. In this case, a list of lists. Later, we can convert these lists of lists to be something a bit more pretty, but it's going to make more sense for us while programming this to keep it in terms a program understands.
So how might we define our game map? We could start by trying something like:
game = (0, 0, 0, 0, 0, 0, 0, 0, 0)
Clearly that's a 3x3 grid, right? Easy enough!
Well, not so fast there, let's print it out:
(0, 0, 0, 0, 0, 0, 0, 0, 0) >>>
Also, this is a tuple, so it's immutable and we can't change it over time. Thus, we shall use lists!
game = [0, 0, 0, 0, 0, 0, 0, 0, 0] print(game)
[0, 0, 0, 0, 0, 0, 0, 0, 0] >>>
Still not quite what we wanted yet. Let's instead convert this to a list of lists.
game = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] print(game)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>>
Still flat, but we can see they're now clearly 3 groups. How can we separate these out? You might ask....
how might we iterate over these?. Ah, a for loop!
game = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for row in game: print(row)
[0, 0, 0] [0, 0, 0] [0, 0, 0] >>>
Now we're making progress! I think we've got our game board to start. So my thinking for now is that 0 means no one has played there, then we'll use the number 1 for player 1 and number 2 for player 2. Later, we can come in and use this list of lists to generate a more pretty version of the game, but, for now, this logic should work well.
So we've got a game board, what's next? We need some way let players play. This step has 2 parts. One part is figuring out where exactly the user wants to play, and the other is actually marking that spot on the game's board. In the next tutorial, we're going to cover how we can determine from the user where they wish to play.