Noughts & Crosses Game in 69 lines of Python code
It seems like many people enjoy tutorials about making games. Well, let me make one too! Today we are going to be implementing the legendary "Noughts and Crosses" game in 69 lines of Python code! I am not going to overcomplicate matters with OOP and all that... a few functions will do.
First, let's create 2 global variables:
M stores our game's 3 x 3 field. Classic. It is a 2D matrix, so I called it
S holds the side: when
S = True, it's X's turn and vice versa.
C holds the number of moves made.
Now, let's write the main function. I called it
xo() for simplicity. It has to:
- Show an empty board
- Start a
whileloop that will repeat itself until
C == 9
- Inside the loop, it has to
- Ask user to make a move
- Check if either of the two players won and if yes,
- If the
whileloop doesn't encounter a
breakon its way, it means that the 9 moves are made, yet no one won, so it must be a tie!
The easiest function to implement is
board_show(). Just print out our little matrix
M. Don't forget to put some empty
turn() function is a bit trickier, yet not too complicated either. We want to:
- Ask player where he/she wants to place his/her mark
- Check if the selected square is free, and if it is, put X or O into it, change the
board_show()to demonstrate the result
- If it's not empty, we want to let the user know that the move was invalid and make him repeat it
Now that we have our
turn() function nice and shining, we only need the
big_check() function, only it's not so easy. The
big_check() isn't called big for no reason -- it consists of three other functions:
check_dig()check both diagonals
But these are fairly simple and you will see why in a second. The only thing we need to do is to check whether all three positions have the same
chr in them that is not
'_' the default one.
Now, let's get to the
big_check(). What it does essentially is it checks every row, column, and diagonal using the functions we've just written and if at least one of those function returns
True, the whole
big_check() function must return
"Now we have everything! It's complete!" -- a newbie would say, but no, it's actually not. There is one last bit to it that will finally make it work -- the 69th line: