Skip to main content

Tic Tac Toe game in Python

This is not a true game, nor either a simulation, but a casual game in the sense that there is no AI in this, but just casual choices, like when players have no strategy at all in the game of the tic tac toe.


It is just an exercize to take confidence with some strategy you could adopt doing a game.
The code is so simple. Very basic. No graphic. It simply displays all the moves (casual moves) of the two players on a grid made by number from 0 to 8.


Let's take a look at the code and the output


from random import shuffle

gr = '012345678'
end = False

print("Let's start...")

def show():
 x = 0
 for i in gr:
  if end == True:
   break
  if x > 2:
   x = 0
   print()
  print(i,end=' ')
  x += 1
 print()
 print()


print()

lgr = list(gr)
shuffle(lgr)

def randomx(x):
 for i in range(x):
  global gr
  pick = lgr.pop()
  gr = gr.replace(pick,"X")
  show()
  pick = lgr.pop()
  gr = gr.replace(pick,"O")
  show()
  allrow()


def rows(*args):
 row = ''
 for i in args:
  row += gr[i]
 return row

def allrow():
 global end
 w = "XXX"
 o = "OOO"
 r1 = rows(0,1,2)
 r2 = rows(3,4,5)
 r3 = rows(6,7,8)
 c1 = rows(0,3,6)
 c2 = rows(1,4,7)
 c3 = rows(2,6,8)
 d1 = rows(0,4,8)
 d2 = rows(2,4,6)

 r = (r1,r2,r3,c1,c2,c3,d1,d2)
 if w in r:
  print("X is the winner")
  end = True
 elif o in r:
  print("O is the winner")
  end = True
 else:
  print("The game goes on\n")
  if len(lgr)>1:
   randomx(1)

allrow()
Let's start...

The game goes on

0 1 2 
X 4 5 
6 7 8 

0 1 2 
X O 5 
6 7 8 

The game goes on

X 1 2 
X O 5 
6 7 8 

X 1 O 
X O 5 
6 7 8 

The game goes on

X 1 O 
X O 5 
6 7 X 

X 1 O 
X O 5 
O 7 X 

Ha vinto lo O


1. showing the grid

from random import shuffle

gr = '012345678'
end = False

print("Let's start...")

def show():
 x = 0
 for i in gr:
  if end == True:
   break
  if x > 2:
   x = 0
   print()
  print(i,end=' ')
  x += 1
 print()
 print()

I imported the shuffle function from the random module.
The I used the string gr for the grid.
In the function show, in fact, I cicled the string with a for loop that printed in the console three caracters, then use print() to go to the next line and then goes on untile the end. At the end it prints a couple of empty line to give space to text in the console output.

2. Casual playing
As I said, the choises of the players are random. I transformed the string '12345678' in al list (lgr). Then I shuffled the list (I could not shuffle the string, because strings are immutable objects in Python).
Then I made the random() function. This has a for loop that is not useful... I made it for other purposes that in the final version in no more necessary, but I left here... it should be deleted... but let's fake is not there. When you call the function the last of the items of the list is picked. It is a casual string... that contains a number... it is casual because I shuffled the lgr list.
I replace the number in gr string ("012345678") with an "X". So now the gr string has been changed in ("01X345678") if the struing with a numer randomly chosen from lgr was "2". As I have popped the element from the list lgr, that element is no more in the list.
 Then I show the grid with the show() function, the I choose randomly where to put the "O" as it was done for the "X".

lgr = list(gr)
shuffle(lgr)

def randomx(x):
 for i in range(x):
  global gr
  pick = lgr.pop()
  gr = gr.replace(pick,"X")
  show()
  pick = lgr.pop()
  gr = gr.replace(pick,"O")
  show()
  allrow()

In the next episode we will explain the rest of the code.

Comments

Popular posts from this blog

Widgets for Jupyter Notebook: a text input widget

Widgets for Jupyter notebook ¶ Let's import the module ipywidgets into the Jupyter Notebook from ipywidgets import widgets from ipywidgets import * from traitlets import * Now we import the display function from IPython ¶ let's attach a function to the event on_submit After we run this cell, we can go up and write something in the text widget and after you submit the text you wrote will be printed after the cell from IPython.display import display text = widgets . Text () display ( text ) def handle_submit ( sender ): print ( "Thank you for entering this text:" , text . value ) text . on_submit ( handle_submit ) Thank you for entering this text: Ciao

Image in Jupyter and PIL step by step

Hi, """ Hi, we will see a step by step tutorial about PIL and IPython.core.display modules to create images from other images and diplaying them in Jupyter notebook """ # What we will do # Create a card # 1. Take a pic of a heart # 2. Create an image blanck the size of a card 90*130 # 3. Paste the heart in the middle # 4. show the card """ As first step wi will simply display an image on the notebook. I will show two way to display the image with 'display' from IPhyton a. Using the open method of PIL.Image (named Img) b. Using the Image method from the IPython.core.display module """ # 1. Take the pic of a heart from IPython.core.display import Image , display from PIL import Image as Img heart = 'img/heart.png' display ( Image ( heart )) display ( Img . open ( heart )) # 2. Create an image blanck the size of a card 90*130 # 3. Paste the heart in the middle #...

Let's draw a circle with PIL in Python

Let's continue making our coding around PIL. Let's start with some basic drawing: a circle from PIL import Image , ImageDraw img = Image . new ( "RGB" ,( 60 , 60 ), 'white' ) dr = ImageDraw . Draw ( img ) dr . ellipse (( 0 , 0 , 60 , 60 ), 'yellow' ) img . show () this is the image produced *If you use jupyter notebook, just write img at the end to see the output.