Skip to content
Sign upLog in
← Back to Community
Noughts & Crosses Game in 69 lines of Python code
Profile icon
sharpvik

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:

# GLOBAL VARIABLES M = [ ['_','_','_'], ['_','_','_'], ['_','_','_'] ] S = True C = 0

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!
# MAIN def xo(): board_show() # FUNCTION NOT YET IMPLEMENTED! while C < 9: turn() # FUNCTION NOT YET IMPLEMENTED! if big_check(): # FUNCTION NOT YET IMPLEMENTED! print(f"{'X' if not S else 'O'} wins!", end="\n\n") break else: # if break not encountered, it must be a tie! print("It's a tie!", end="\n\n")

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!

def board_show(): print() for y in range(3): print(" ", end="") for x in range(3): print(M[y][x], end=" ") print() print()

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
def turn(): global S, C # allows us to reference S that is not assigned in this scope pos = [ ( int(i) - 1 ) for i in input("Your move: ").split() ] # this produces a list of two int values X and Y # it reduces each one by 1 since computer (unlike human) starts counting from 0 x, y = pos[0], pos[1] # save x and y separately for clearance if M[y][x] == '_': M[y][x] = 'X' if S else 'O' S = not S C += 1 # increment move counter C by 1 only if the move is valid board_show() else: print("Invalid move!")

This file cannot be displayed: https://storage.googleapis.com/replit/images/1540691236971_2da5aa0c94f249f1a54fbf72e58e12be.pn

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.

def check_hr(y): return M[y][0] == M[y][1] == M[y][2] != '_' def check_vr(x): return M[0][x] == M[1][x] == M[2][x] != '_' def check_dig(): return M[0][0] == M[1][1] == M[2][2] != '_' or \ M[0][2] == M[1][1] == M[2][0] != '_'

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!

def big_check(): win = False for i in range(3): if check_hr(i) or check_vr(i): win = True if check_dig(): win = True return win

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

xo() # invoke the xo() function
Voters
Profile icon
ch1ck3n
Profile icon
CAINMEADEN
Profile icon
CadenVaughan1
Profile icon
datboicatguy
Profile icon
CollinKunsman
Profile icon
Makrayne
Profile icon
ALEJANDROFLOR11
Profile icon
Mosrod
Profile icon
jeff7
Profile icon
timmy_i_chen
Comments
hotnewtop
Profile icon
furrycode

"69 lines"...
nice

Profile icon
fortune69

@furrycode
( ͡° ͜ʖ ͡°) XD

Profile icon
timmy_i_chen

Great visuals - thanks for making this!

Profile icon
sharpvik

@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.

Profile icon
CollinKunsman

I- okay XD

Profile icon
fortune69

NOICE

Profile icon
PlsDont

how do i play the game itself?

Profile icon
KlintSmith

@PlsDont
The imaginative improvement that is known as Crazy time utilizes a fortunate wheel planned in the style of a "Dreamcatcher" with 54 sections, in which liberal prizes from 1x to 10x are situated, as well as 4 extra choices: Coin Flip, Pachinko, Cash Hunt and Crazy Time. The worldwide game producer Evolution, who made this item, is exceptionally defensive of its betting meeting instrument and doesn't unveil many subtleties that might be helpful for a right numerical investigation of the wagering process.In Crazy time(https://www.9winz.com/home/blog/how-to-play-crazy-time-and-win-1), the actual wheel is significant. The seller is liable for sending off ensuing new meetings by turning the drum. The outcome in the wake of looking over the reel can be either a number (1, 2, 5 or 10), or one of four cash positions (Coin Flip, Crazy Time, Cash Hunt or Pachinko). In the event that the reel stops at a specific number, the award will be equivalent to this pointer, expanded by the size of the bet. For instance, when the reel lands on winning number two, you can win two times your stake. Every one of extra choices have their own principles and their own payout component. Every reward round brings about an award that is a different of the first reward bet. What makes the gaming meeting considerably more energizing is the chance to build the rewards with an extra multiplier chose prior to turning the primary wheel while choosing the top space. This can prompt extra compensations during reward draws.It is vital to take note of that Crazy time is a fairly complicated framework, which is the reason most clients will generally pursue apparently simple rewards. In spite of the fact that there are the absolute greatest awards, any fruitful strategy at crazy times is really revolved around "number wagers." They get multipliers from the top space, so the successes in the end will be exceptionally noteworthy. Thus, the extra choices Coin Flip and Pachinko have the most reduced return on the rundown, Cash Hunt is the normal, and Crazy Time is by a long shot awesome of all. As needs be, to build the possibilities winning, you ought to have a functioning wagered on an extra situation in the wagering network.

Profile icon
mmf045

what are the controls

Profile icon
fortune69

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

Profile icon
mmf045