Learn to Code via Tutorials on Repl.it!

← Back to all posts
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 M. 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:

  1. Show an empty board
  2. Start a while loop that will repeat itself until C == 9
  3. Inside the loop, it has to
    1. Ask user to make a move
    2. Check if either of the two players won and if yes, break itself
  4. If the while loop doesn't encounter a break on 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 prints for spacing purposes!

Now, the turn() function is a bit trickier, yet not too complicated either. We want to:

  1. Ask player where he/she wants to place his/her mark
  2. Check if the selected square is free, and if it is, put X or O into it, change the State, and board_show() to demonstrate the result
  3. 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:

  1. check_hr(y) check yth row
  2. check_vr(x) check xth column
  3. 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 True!

"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:


"69 lines"...


@furrycode ( ͡° ͜ʖ ͡°) XD


Great visuals - thanks for making this!


@timmy_i_chen In my repls I now have Noughts & Crosses (Web) repo in which you'll find the same game but in HTML format. No need to calculate coordinates! Go check it out.


I- okay XD




how do i play the game itself?


what are the controls


@mmf045 use coordinates, for example: 1 1 or 2 3