python project with implementation which game Tic Tac Toe with code

 

      ##      INFORMATION TO TIC TAC TOE GAME       ##     

    It's no doubt, you must have played tic tac toe in your school day and every one of us loves to play the game. you will be surprised to know that the game of tic tac toe is knows to exist since ancient Egypt times. 

                      Tic Tac To is one of the most played games and is the best time killer game that you can play any where with to play this game don't worry let as first understand that.

the game is played be two individuals. first we draw a board with 3*3 square grid. the first played chooses ['X'] and draws it on any of the square grid. The first played chooses ['X'] and draw it on any of the square grid, them it's the chance of the second played to draw ['O'] on the available spaces. Like this, the players draw ['X'] and ['O'] alternatively on the empty spaces until a player success in the horizontal, vertical or diagonal way. then the player wins the game otherwise the game draw when all spots are filled.


# Tic Tac Toe - About the python project .

The interesting python project will be build using he pygame library. We will be explaining all this pygame. Object method that are used in this project. pygame is a great library that will allows us to create the windows and draw images and shapes on the windows. This way we will capture mouse coordinates and identity the block where need to mark b 'X' or 'O' then we will check if the user wins the game or not. 

Prerequisites :-                                                                                                              To implement his game, we will use the basic connects of python and pygame which is a python library for building cross-platform games. It contains the modules need for computer graphics and sound libraries. To install the library, you can use pip installer from the command line. 

    ⇛. Pip install pygame.

    first, yets check the steps to build tic tac toe program in python 

Create the display windows for our game.

⇒Draw the grid on the canvas where, we will w play tic tac toe. 

⇒Draw the status bar below the canvas to show which player's true is it and who wins the game.

⇒When someone wins the game or the game is a draw the we reset the game.


We need to run our game inside an infinite  loop. it will continuously look for event and when a user presses the mouse button on the grid we will first get the X and Y coordinates of the mouse. Then we will check which square  the user has clicked. Then we will draw the appropriate 'X'  OR 'O' image on the canvas. so that is basically what will do in python project idea.

1. Initializing Game Components:- 

 So let's start by importing the pygame library and the time library because we will use the time.sleep() method to pause game at certain positions. Then we initialize all the global variable that we will use in our Tic Tac Toe game.

import pygame as pg , sys from pygame.locals import* import time  # initialize global variables  XO = 'x' Winner = None  draw = false width = 400 height = 400 white = (255, 255, 255) line-color = (10, 10, 10) #Tic Tac Toe 3*3 board  TTT = [[None]*3, [None]*3, [none]*3]

Here, the TTT is the main 3*3 Tic Tac Toe board and at first, it will have i none values. The height and width of the canvas where we will play the game is 400*400

2. Initializing  pygame window :- 

We use the pygame to create a new window where we will play our Tic Tac Toe game. So we initialize the pygame with pg.init() method and the window display is set with a width of 400 and a height of 500. We have revered 100-pixel space for displaying the status of the game.


- The pg.display.set-mode() initializes the display and we reference it with the screen variable. This screen variable will be used whenever we want to draw something on the display.


- The pg.display.set-caption method is used to set a name that will appear at the top of the display

# initializing pygame windows pg.init()fps= 30clock = pg.display.set_mode((width, height + 100), 0, 32)pg.display.set_caption("Tic Tac Toe")

3. Load and transform image :-

 The python machine learning project uses many image like the opening image that will display when the game start or reset. The X and O image that we will draw when the user click on the grid. We load all the images.

# loading the images. opening = pg.image.load ('tic tac toe opening.png')X-img = pg.image.load('x.png')  O-img = pg.image.load('o.png')   # resting images  X-img = pg.transform.scale (x-img, (80, 80))   O-img = pg.transform.scale(o-img, (80, 80))opening = pg.transform.scale(opening, [width,height+100))    

4.  Define the functions:- 

 Now, we create a function that will start the game. We will also use this function when we want to restart the game. In pygame, the blit() function is used on the surface to draw an image on top of another image.

- So we draw the opening image and after drawing we always need to update the display with pg.display.update(). When the opening image is draw, we wait for 1 second using time.sleep(1) and fill the screen with white color.

- Next, we draw 2 vertical and horizontal line on the white background to ,make the 3*3 grid. In the end, we call the draw-status() function. 

def game-opening():  Screen.blit (opening,(0,0))   pg.display.update()  time.sleep(1) Screen.fill(white) # Drawing vertical lines pg.draw.line( screen, line-color) (width/3, 0), (width/3, height). 7)  pg.draw.line(screen, line-color, (width/3*2, height) 7)   # Drawing horizontal line   pg.draw.line(screen, line-color, (0, height/3), (width, height/3), 7) pg.draw.line (screen, line-color, (0,height/3*2), (width, height/3*2),7)  draw-status()                                                                  

The draw-status() function draws a block rectangle where we update the status of the game showing which player's turn is it and whether the game ends or draws  

def draw-status():    global draws    if winner is None: message = xo.upper() + "'s Turn" else:message = winner.upper() + "Won!"  if draw:  message = 'Game Draw!'font = pg.font.Font (None, 30)text = Font.render (message, 1, (255, 255, 255))   # copy the rendered message onto the board.Screen.fill ((0,0,0), (0,400, 500, 100))   text-rect = text.get_rect(center= (width/2, 500-50)) Screen.blit(text, text_rect)pg.display.update()    

 The check-win() function checks the Tic Tac Toe board to see all the marks of 'X' and 'O'. It calculates whether a p-layer has won the game or not. They can either win when the player has marked 3 consecutive marks in a row, columns or diagonally. This function is called every time when we draw a mark 'X' OR 'O' on the board.

def check-Win():  global TTT, Winner, draw  # check for winning rows for row in range(0,3): if ((TTT[row][0]==TTT[row][1]==TTT[row][2]) and (TTT[row][0] is not None)):  Winner = TTT [row] [0]    pg.draw.line(screen, (255,0,0), (0,(row+1)*height/3-height/6), / (width, (row+1)*height/3-height/6),4)  break   # check for wining columns   for col in range(0,3):  if (TTT[0][col] == TTT[1][col]==TTT[2][col]) and (TTT[0][col] is not None):  # This column won. Winner = TTT[0][col]   # Draw wining line pg.draw.line(screen, (250,0,0), ((col+1)*width/3-width/6,0), / ((col+1)*-width/3 - width/6, height), 4)    break    # check for diagonal winners  if (TTT[0][0]==TTT[1][1]==TTT[2][2]) and (TTT [0][0] is not None):  # Game won diagonally left to right  Winner = TTT[0][0]   pg.draw.line(screen, (250,70,70), (50,50),(350,350),4)   if (TTT [0][2] ==TTT[1][1]==TTT[2][0])and (TTT [0][2] is not None): # Game won diagonally right to left  Winner = TTT [0][2]pg.draw.line(screen, (250,70,70), (305,50),(50,350),4)  if (all ([all(row) for row in TTT]) and winner is None):draw = Truedraw_status()                             

The draw XO (row, col) function takes the row and column where the mouse is clicked and then it draws the 'X' or 'O' mark. We calculate the X and Y coordinates of the starting point from where we will draw the png image of the mark.

def draw XO (row ,column):global TTT, XO if row == 1: posx = 30  if row ==2: posx = width/3 +30   if col ==1:  posy = 30if col ==2:  posy == height/3 +30  if col ==3: posy = height/3*2 +30  TTT[row-1][col-1] = xoif (xo == 'x'): Screen.blit (x_img,(posy,posx))  xo = 'o'  else: Screen.blit(o-img,(posy,posx))  XO = 'x' pg.display.update()  #print(posx, posy)  #print(TTT)                                 

The user-click() function is triggered every time the user presses the mouse button.

When the user clicks the mouse, we first take the X and Y coordinates of where the mouse is clicked on the display windows and then, if that place is not occupied we draw the 'XO' on the canvas. We also check if the player or not after drawing 'XO on the board.  

def user-Click ()#Get coordinates of mouse click X,Y = pg.mouse.get_pos()  #Get column of mouse click (1-3) if (x<width/3): col = 1 elif (x < width/3*2):col = 2   elif(x <width): col = 3 else:   col = None # Get row of mouse click (1-3)  if (y< height/3): row = 1 elif ( Y< height/3*2):  row =2elif (y < height):   row = 3   else:   row = None  # print (row, col) if( row and col and TTT [row-1] [col-1] is None ):  global xo # Draw the X or O on screen draw XO (row , col)check-win()              

The last function is the reset- game (). This will restart the game and we also reset all the variables to the beginning of the game. 

def reset_game():  global TTT, winner, XO, draw time.  sleep(3) XO ='x'draw = false game_opening()TTT = [[None]*3, [None]*3, [None]*3]         

5. Run the game forever.   :-                                                                                                      To start the game,we will call the game_opening() function. Then, we run an infinite loop and continuously  check for any event made by the user. If the user presses mouse button, the mousebuttondown event will be captured and then we will trigger the userclick() function. Then if the wins or the game draws, reset the game  calling reset_game() function.We update the display in each iteration and we have set the frames per second to 30.

game_opening() #run the game loop forever   while(True):  for even in pg.event.get(): if event.type == Quit: pg.quit() sys.exit()   elif event.type is MOUSEBUTTONDOWN   # The clicked; please an X or O userclick() if (winner or draw):  rest_game() pg.display.update()look.tick(fps)                                             

Ho ray  ! the game is complete and ready to play . Save the source code with the viruschandu.pg file name band run the file.

Post a Comment

1 Comments

  1. Hello friends you learn code language, your future career goods and please comment or computer language code are good perfect run

    ReplyDelete