Chuyển tới nội dung
Home » Xo Game In Python | Condition For Wiining

Xo Game In Python | Condition For Wiining

Python TIC TAC TOE Tutorial | Beginner Friendly Tutorial

Playing computer games is a great way to unwind or challenge yourself. Some people even do it professionally. It’s also fun and educational to build your own computer games. In this tutorial, you’ll build a classic tic-tac-toe game using Python and Tkinter.

With this project, you’ll go through the thought processes required for creating your own game. You’ll also learn how to integrate your diverse programming skills and knowledge to develop a functional and fun computer game.

In this tutorial, you’ll learn how to:

  • Program the classic tic-tac-toe game’s logic using Python
  • Create the game’s graphical user interface (GUI) using the Tkinter tool kit
  • Integrate the game’s logic and GUI into a fully functional computer game

As mentioned, you’ll be using the Tkinter GUI framework from the Python standard library to create your game’s interface. You’ll also use the model-view-controller pattern and an object-oriented approach to organize your code. For more on these concepts, check out the links in the prerequisites.

To download the entire source code for this project, click the link in the box below:

Get Source Code: Click here to get access to the source code that you’ll use to build your tic-tac-toe game.

Rules of Game

  1. Traditionally the first player plays with “X”. So you can decide who wants to go with “X” and who wants to go with “O”.
  2. Only one player can play at a time.
  3. If any of the players have filled a square, then the other player and the same player cannot override that square.
  4. There are only two conditions that may match will be a draw or may win.
  5. The player who succeeds in placing three respective marks (X or O) in a horizontal, vertical, or diagonal row wins the game.

Requirements

The requirement for building the tic tac toe python are listed below:

  • Good knowledge of Python Basics and refreshing the topics as mentioned under the subheading Pre-requisites.
  • Command line Interface or any local Terminal to build the tic tac toe python.
  • Text editor: We can use either VSCode Python 3 installed on your machine or we can implement the source code with any Python online compiler as well.
Python TIC TAC TOE Tutorial | Beginner Friendly Tutorial
Python TIC TAC TOE Tutorial | Beginner Friendly Tutorial

Demo: A Tic-Tac-Toe Game in Python

In this step-by-step project, you’ll build a tic-tac-toe game in Python. You’ll use the Tkinter tool kit from the Python standard library to create the game’s GUI. In the following demo video, you’ll get a sense of how your game will work once you’ve completed this tutorial:

Your tic-tac-toe game will have an interface that reproduces the classic three-by-three game board. The players will take turns making their moves on a shared device. The game display at the top of the window will show the name of the player who gets to go next.

If a player wins, then the game display will show a winning message with the player’s name or mark (X or O). At the same time, the winning combination of cells will be highlighted on the board.

Finally, the game’s File menu will have options to reset the game if you want to play again or to exit the game when you’re done playing.

If this sounds like a fun project to you, then read on to get started!

Prerequisites

To complete this tic-tac-toe game project, you should be comfortable or at least familiar with the concepts and topics covered in the following resources:

  • Python GUI Programming With Tkinter
  • Object-Oriented Programming (OOP) in Python 3
  • Python “for” Loops (Definite Iteration)
  • When to Use a List Comprehension in Python
  • Model-View-Controller (MVC) Explained – With Legos
  • Dictionaries in Python
  • How to Iterate Through a Dictionary in Python
  • Main Functions in Python
  • Write Pythonic and Clean Code With namedtuple

If you don’t have all of the suggested knowledge before starting this tutorial, that’s okay. You’ll learn by doing, so go ahead and give it a whirl! You can always stop and review the resources linked here if you get stuck.

Python Tic Tac Toe game ⭕
Python Tic Tac Toe game ⭕

Step 1: Set Up the Tic-Tac-Toe Game Board With Tkinter

To kick things off, you’ll start by creating the game board. Before doing this, you need to decide how to organize the code for your tic-tac-toe game. Because this project will be fairly small, you can initially keep all the code in a single

.py

file. This way, running the code and executing your game will be more straighforward.

Go ahead and fire up your favorite code editor or IDE. Then create a

tic_tac_toe.py

file in your current working directory:


# tic_tac_toe.py """A tic-tac-toe game built with Python and Tkinter."""

Throughout this tutorial, you’ll be incrementally adding code to this file, so keep it open and near. If you want to get the entire code for this tic-tac-toe game project, then you can click the following collapsible section and copy the code from it:


"""A tic-tac-toe game built with Python and Tkinter.""" import tkinter as tk from itertools import cycle from tkinter import font from typing import NamedTuple class Player(NamedTuple): label: str color: str class Move(NamedTuple): row: int col: int label: str = "" BOARD_SIZE = 3 DEFAULT_PLAYERS = ( Player(label="X", color="blue"), Player(label="O", color="green"), ) class TicTacToeGame: def __init__(self, players=DEFAULT_PLAYERS, board_size=BOARD_SIZE): self._players = cycle(players) self.board_size = board_size self.current_player = next(self._players) self.winner_combo = [] self._current_moves = [] self._has_winner = False self._winning_combos = [] self._setup_board() def _setup_board(self): self._current_moves = [ [Move(row, col) for col in range(self.board_size)] for row in range(self.board_size) ] self._winning_combos = self._get_winning_combos() def _get_winning_combos(self): rows = [ [(move.row, move.col) for move in row] for row in self._current_moves ] columns = [list(col) for col in zip(*rows)] first_diagonal = [row[i] for i, row in enumerate(rows)] second_diagonal = [col[j] for j, col in enumerate(reversed(columns))] return rows + columns + [first_diagonal, second_diagonal] def toggle_player(self): """Return a toggled player.""" self.current_player = next(self._players) def is_valid_move(self, move): """Return True if move is valid, and False otherwise.""" row, col = move.row, move.col move_was_not_played = self._current_moves[row][col].label == "" no_winner = not self._has_winner return no_winner and move_was_not_played def process_move(self, move): """Process the current move and check if it's a win.""" row, col = move.row, move.col self._current_moves[row][col] = move for combo in self._winning_combos: results = set(self._current_moves[n][m].label for n, m in combo) is_win = (len(results) == 1) and ("" not in results) if is_win: self._has_winner = True self.winner_combo = combo break def has_winner(self): """Return True if the game has a winner, and False otherwise.""" return self._has_winner def is_tied(self): """Return True if the game is tied, and False otherwise.""" no_winner = not self._has_winner played_moves = ( move.label for row in self._current_moves for move in row ) return no_winner and all(played_moves) def reset_game(self): """Reset the game state to play again.""" for row, row_content in enumerate(self._current_moves): for col, _ in enumerate(row_content): row_content[col] = Move(row, col) self._has_winner = False self.winner_combo = [] class TicTacToeBoard(tk.Tk): def __init__(self, game): super().__init__() self.title("Tic-Tac-Toe Game") self._cells = {} self._game = game self._create_menu() self._create_board_display() self._create_board_grid() def _create_menu(self): menu_bar = tk.Menu(master=self) self.config(menu=menu_bar) file_menu = tk.Menu(master=menu_bar) file_menu.add_command(label="Play Again", command=self.reset_board) file_menu.add_separator() file_menu.add_command(label="Exit", command=quit) menu_bar.add_cascade(label="File", menu=file_menu) def _create_board_display(self): display_frame = tk.Frame(master=self) display_frame.pack(fill=tk.X) self.display = tk.Label( master=display_frame, text="Ready?", font=font.Font(size=28, weight="bold"), ) self.display.pack() def _create_board_grid(self): grid_frame = tk.Frame(master=self) grid_frame.pack() for row in range(self._game.board_size): self.rowconfigure(row, weight=1, minsize=50) self.columnconfigure(row, weight=1, minsize=75) for col in range(self._game.board_size): button = tk.Button( master=grid_frame, text="", font=font.Font(size=36, weight="bold"), fg="black", width=3, height=2, highlightbackground="lightblue", ) self._cells[button] = (row, col) button.bind("

", self.play) button.grid(row=row, column=col, padx=5, pady=5, sticky="nsew") def play(self, event): """Handle a player's move.""" clicked_btn = event.widget row, col = self._cells[clicked_btn] move = Move(row, col, self._game.current_player.label) if self._game.is_valid_move(move): self._update_button(clicked_btn) self._game.process_move(move) if self._game.is_tied(): self._update_display(msg="Tied game!", color="red") elif self._game.has_winner(): self._highlight_cells() msg = f'Player "{self._game.current_player.label}" won!' color = self._game.current_player.color self._update_display(msg, color) else: self._game.toggle_player() msg = f"{self._game.current_player.label}'s turn" self._update_display(msg) def _update_button(self, clicked_btn): clicked_btn.config(text=self._game.current_player.label) clicked_btn.config(fg=self._game.current_player.color) def _update_display(self, msg, color="black"): self.display["text"] = msg self.display["fg"] = color def _highlight_cells(self): for button, coordinates in self._cells.items(): if coordinates in self._game.winner_combo: button.config(highlightbackground="red") def reset_board(self): """Reset the game's board to play again.""" self._game.reset_game() self._update_display(msg="Ready?") for button in self._cells.keys(): button.config(highlightbackground="lightblue") button.config(text="") button.config(fg="black") def main(): """Create the game's board and run its main loop.""" game = TicTacToeGame() board = TicTacToeBoard(game) board.mainloop() if __name__ == "__main__": main()

Having the entire source code beforehand will allow you to check your progress while going through the tutorial.

Alternatively, you can also download the game source code from GitHub by clicking the link in the box below:

Get Source Code: Click here to get access to the source code that you’ll use to build your tic-tac-toe game.

Now that you know what the game’s final code will look like, it’s time to make sure you have the right Tkinter version for this project. Then, you’ll go ahead and create your game board.

Ensure the Right Tkinter Version

To complete this project, you’ll use a standard Python installation. There’s no need to create a virtual environment because no external dependency is required. The only package that you’ll need is Tkinter, which comes with the Python standard library.

However, you need to make sure that you have the right Tkinter version installed. You should have Tkinter greater than or equal to 8.6. Otherwise, your game won’t work.

You can check your current Tkinter version by starting a Python interactive session and running the following code:


>>> import tkinter >>> tkinter.TkVersion 8.6

If this code doesn’t show a version greater than or equal to 8.6 for your Tkinter installation, then you’ll need to fix that.

On Ubuntu Linux, you may need to install the

python3-tk

package using the system’s package manager,

apt

. That’s because typically Ubuntu doesn’t include Tkinter in its default Python installation.

Once you have Tkinter properly installed, then you need to check its current version. If the Tkinter version is lower than 8.6, then you’ll have to install a more recent version of Python either by downloading it from the official download page or by using a tool like pyenv or Docker.

On macOS and Windows, a straightforward option is to install a Python version greater than or equal to 3.9.8 from the download page.

Once you’re sure you have the right Tkinter version, you can get back to your code editor and start writing code. You’ll begin with the Python class that’ll represent the tic-tac-toe game board.

Create a Class to Represent the Game Board

To build the board of your tic-tac-toe game, you’ll use the

Tk

class, which allows you to create the main window of your Tkinter app. Then you’ll add a display on a top frame and a grid of cells covering the rest of the main window.

Go ahead and import the required objects and define the board class:


# tic_tac_toe.py import tkinter as tk from tkinter import font class TicTacToeBoard(tk.Tk): def __init__(self): super().__init__() self.title("Tic-Tac-Toe Game") self._cells = {}

In this code snippet, you first import

tkinter

as

tk

to bring the module’s name to your current namespace. Using the

tk

abbreviation is a common practice when it comes to using Tkinter in your code.

Then you import the

font

module directly from

tkinter

. You’ll use this module later in this tutorial to tweak the font of your game display.

The

TicTacToeBoard

class inherits from

Tk

, which makes it a full-fledged GUI window. This window will represent the game board. Inside

.__init__()

, you first call the superclass’s

.__init__()

method to properly initialize the parent class. To do this, you use the built-in super() function.

The

.title

attribute of

Tk

defines the text to show on the window’s title bar. In this example, you set the title to the

"Tic-Tac-Toe Game"

string.

The

._cells

non-public attribute holds an initially empty dictionary. This dictionary will map the buttons or cells on the game board to their corresponding coordinates—row and column—on the grid. These coordinates will be integer numbers reflecting the row and column where a given button will appear.

To continue with the game board, you now need to create a display where you can provide information about the game’s state and result. For this display, you’ll use a

Frame

widget as the display panel and a

Label

widget to show the required information.

Note: The line numbers in the code samples in this tutorial are intended to facilitate the explanation. Most of the time, they won’t match the line numbers in your final script.

Now go ahead and add the following method to your

TicTacToeBoard

class:


1# tic_tac_toe.py 2# ... 3 4class TicTacToeBoard(tk.Tk): 5 # ... 6 7 def _create_board_display(self): 8 display_frame = tk.Frame(master=self) 9 display_frame.pack(fill=tk.X) 10 self.display = tk.Label( 11 master=display_frame, 12 text="Ready?", 13 font=font.Font(size=28, weight="bold"), 14 ) 15 self.display.pack()

Here’s a breakdown of what this method does line by line:

  • Line 8 creates a


    Frame

    object to hold the game display. Note that the

    master

    argument is set to

    self

    , which means that the game’s main window will be the frame’s parent.

  • Line 9 uses the


    .pack()

    geometry manager to place the frame object on the main window’s top border. By setting the

    fill

    argument to

    tk.X

    , you ensure that when the user resizes the window, the frame will fill its entire width.

  • Lines 10 to 14 create a


    Label

    object. This label needs to live inside the frame object, so you set its

    master

    argument to the actual frame. The label will initially show the text

    "Ready?"

    , which indicates that the game is ready to go, and the players can start a new match. Finally, you change the label’s font size to

    28

    pixels and make it bold.

  • Line 15 packs the display label inside the frame using the


    .pack()

    geometry manager.

Cool! You already have the game display. Now you can create the grid of cells. A classic tic-tac-toe game has a three-by-three grid of cells.

Here’s a method that creates the grid of cells using

Button

objects:


1# tic_tac_toe.py 2# ... 3 4class TicTacToeBoard(tk.Tk): 5 # ... 6 7 def _create_board_grid(self): 8 grid_frame = tk.Frame(master=self) 9 grid_frame.pack() 10 for row in range(3): 11 self.rowconfigure(row, weight=1, minsize=50) 12 self.columnconfigure(row, weight=1, minsize=75) 13 for col in range(3): 14 button = tk.Button( 15 master=grid_frame, 16 text="", 17 font=font.Font(size=36, weight="bold"), 18 fg="black", 19 width=3, 20 height=2, 21 highlightbackground="lightblue", 22 ) 23 self._cells[button] = (row, col) 24 button.grid( 25 row=row, 26 column=col, 27 padx=5, 28 pady=5, 29 sticky="nsew" 30 )

Wow! This method does a lot! Here’s an explanation of what each line does:

  • Line 8 creates a


    Frame

    object to hold the game’s grid of cells. You set the

    master

    argument to

    self

    , which again means that the game’s main window will be the parent of this frame object.

  • Line 9 uses the


    .pack()

    geometry manager to place the frame object on the main window. This frame will occupy the area under the game display, all the way to the bottom of the window.

  • Line 10 starts a loop that iterates from

    to. These numbers represent the row coordinates of each cell in the grid. For now, you’ll haverows on the grid. However, you’ll change this magic number later and provide the option of using a different grid size, such as four by four.

  • Line 11 and 12 configure the width and minimum size of every cell on the grid.

  • Line 13 loops over the three column coordinates. Again you use three columns, but you’ll change this number later to provide more flexibility and get rid of magic numbers.

  • Lines 14 to 22 create a


    Button

    object for every cell on the grid. Note that you set several attributes, including

    master

    ,

    text

    ,

    font

    , and so on.

  • Line 23 adds every new button to the


    ._cells

    dictionary. The buttons work as keys, and their coordinates—expressed as

    (row, col)

    —work as values.

  • Lines 24 to 30 finally add every button to the main window using the


    .grid()

    geometry manager.

Now that you’ve implemented

._create_board_display()

and

._create_board_grid()

, you can call them from the class initializer. Go ahead and add the following two lines to

.__init__()

in your

TicTacToeBoard

class:


# tic_tac_toe.py # ... class TicTacToeBoard(tk.Tk): def __init__(self): super().__init__() self.title("Tic-Tac-Toe Game") self._cells = {} self._create_board_display() self._create_board_grid()

These two lines put together the game board by adding the display and grid of cells. Isn’t that cool?

With these updates, you can almost run your app and see how your tic-tac-toe game will look. You just need to write a few more lines of boilerplate code. You need to instantiate

TicTacToeBoard

and call its

.mainloop()

method to launch your Tkinter app.

Go ahead and add the following piece of code to the end of your

tic_tac_toe.py

file:


# tic_tac_toe.py # ... def main(): """Create the game's board and run its main loop.""" board = TicTacToeBoard() board.mainloop() if __name__ == "__main__": main()

This code snippet defines a

main()

function for your game. Inside this function, you first instantiate

TicTacToeBoard

and then run its main loop by calling

.mainloop()

.

The

if __name__ == "__main__":

construct is a common pattern in Python applications. It allows you to control the execution of your code. In this case, the call to

main()

will only happen if you run the

.py

file as an executable program, as opposed to an importable module.

That’s it! You’re now ready to run your game for the first time. Of course, the game isn’t playable yet, but the board is ready. To run the game, go ahead and execute the following command on your command line:


$ python tic_tac_toe.py

Once you’ve run this command, then you’ll get the following window on your screen:

Cool! Your tic-tac-toe game is starting to look like the real thing. Now you need to make this window respond to the players’ actions on the board.

Project Overview

Your goal with this project is to create a tic-tac-toe game in Python. For the game interface, you’ll use the Tkinter GUI tool kit, which comes in the standard Python installation as an included battery.

The tic-tac-toe game is for two players. One player plays X and the other plays O. The players take turns placing their marks on a grid of three-by-three cells. If a given player gets three marks in a row horizontally, vertically, or diagonally, then that player wins the game. The game will be tied if no one gets three in a row by the time all the cells are marked.

With these rules in mind, you’ll need to put together the following game components:

  • The game’s board, which you’ll build with a class called

    TicTacToeBoard
  • The game’s logic, which you’ll manage using a class called

    TicTacToeGame

The game board will work as a mix between view and controller in a model-view-controller design. To build the board, you’ll use a Tkinter window, which you can create by instantiating the

tkinter.Tk

class. This window will have two main components:

  1. Top display: Shows information about the game’s status
  2. Grid of cells: Represents previous moves and available spaces or cells

You’ll create the game display using a

tkinter.Label

widget, which allows you to display text and images.

For the grid of cells, you’ll use a series of

tkinter.Button

widgets arranged in a grid. When a player clicks one of these buttons, the game logic will run to process the player’s move and determine whether there’s a winner. In this case, the game logic will work as the model, which will manage the data, logic, and rules of your game.

Now that you have a general idea of how to build your tic-tac-toe game, you should check out a few knowledge prerequisites that’ll allow you to get the most out of this tutorial.

Multiplayer Tic-Tac-Toe Game in Python
Multiplayer Tic-Tac-Toe Game in Python

Step 5: Provide Options to Play Again and Exit the Game

In this section, you’ll provide your tic-tac-toe game with a main menu. This menu will have an option to restart the game so that the players can start another match. It’ll also have an option to exit the game once the players have finished playing.

Main menus are often an essential component of many GUI applications. So, learning how to create them in Tkinter is a good exercise to improve your GUI-related skills beyond the game development itself.

This is an example of how building your own games is a powerful learning experience because it allows you to integrate knowledge and skills that you can later use in other non-game projects.

The complete source code for this step is available for download. Just click the link below and navigate to the

source_code_step_5/

folder:

Get Source Code: Click here to get access to the source code that you’ll use to build your tic-tac-toe game.

Build the Game’s Main Menu

To add a main menu to a Tkinter application, you can use the

tkinter.Menu

class. This class allows you to create a menu bar on top of your Tkinter window. It also allows you to add dropdown menus to the menu bar.

Here’s the code that creates and adds a main menu to your tic-tac-toe game:


1# tic_tac_toe.py 2# ... 3 4class TicTacToeBoard(tk.Tk): 5 def __init__(self, game): 6 # ... 7 8 def _create_menu(self): 9 menu_bar = tk.Menu(master=self) 10 self.config(menu=menu_bar) 11 file_menu = tk.Menu(master=menu_bar) 12 file_menu.add_command( 13 label="Play Again", 14 command=self.reset_board 15 ) 16 file_menu.add_separator() 17 file_menu.add_command(label="Exit", command=quit) 18 menu_bar.add_cascade(label="File", menu=file_menu)

Here’s what this code does line by line:

  • Line 8 defines a helper method called


    ._create_menu()

    to handle the menu creation in a single place.

  • Line 9 creates an instance of


    Menu

    , which will work as the menu bar.

  • Line 10 sets the menu bar object as the main menu of your current Tkinter window.

  • Line 11 creates another instance of


    Menu

    to provide a File menu. Note that the

    master

    argument in the class constructor is set to your menu bar object.

  • Lines 12 to 15 add a new menu option to the File menu using the


    .add_command()

    method. This new option will have the label

    "Play Again"

    . When a user clicks this option, the application will run the

    .reset_board()

    method, which you provided through the

    command

    argument. You’ll write this method in the following section.

  • Line 16 adds a menu separator using the


    .add_separator()

    method. Separators are useful when you need to separate groups of related commands in a given dropdown menu.

  • Line 17 adds an Exit command to the File menu. This command will make the game exit by calling the


    quit()

    function.

  • Line 18 finally adds the File menu to the menu bar by calling


    .add_cascade()

    with appropriate arguments.

To actually add the main menu to your game’s main window, you need to call

._create_menu()

from the initializer of

TicTacToeBoard

. So, go ahead and add the following line to the class’s

.__init__()

method:


# tic_tac_toe.py # ... class TicTacToeBoard(tk.Tk): def __init__(self, game): super().__init__() self.title("Tic-Tac-Toe Game") self._cells = {} self._game = game self._create_menu() self._create_board_display() self._create_board_grid() # ...

With this final update, your game’s main menu is almost ready for use. However, before using it, you must implement the

.reset_board()

method. That’s what you’ll do in the following section in order to allow the players to play again.

Implement the Play Again Option

To reset the game board and allow the players to play again, you need to add code to both classes,

TicTacToeGame

and

TicTacToeBoard

.

In the game logic class, you need to reset the

._current_moves

attribute to hold a list of initially empty

Move

objects. You also need to reset the

._has_winner

and

.winner_combo

to their initial state. On the other hand, in the game board class, you need to reset the board display and cells to their initial state.

Get back to

TicTacToeGame

in your code editor and add the following method right at the end of the class:


# tic_tac_toe.py # ... class TicTacToeGame(tk.Tk): # ... def reset_game(self): """Reset the game state to play again.""" for row, row_content in enumerate(self._current_moves): for col, _ in enumerate(row_content): row_content[col] = Move(row, col) self._has_winner = False self.winner_combo = []

The

for

loop in

.reset_game()

sets all the current moves to an empty

Move

object. An empty move’s main characteristic is that its

.label

attribute holds the empty string,

""

.

After updating the current moves, the methods sets

._has_winner

to

False

and

.winner_combo

to an empty list. These three resets ensure that the game’s abstract representation is ready to start a new match.

Note that

reset_game()

doesn’t reset the player back to X when preparing the game for a new match. Typically, the winner of the previous match gets to go first in the next one. So, there’s no need to reset the player here.

Once you’ve provided the required new functionality in the game logic, then you’re ready to update the game board functionality. Go ahead and add the following method to the end of

TicTacToeBoard

:


1# tic_tac_toe.py 2# ... 3 4class TicTacToeBoard(tk.Tk): 5 # ... 6 7 def reset_board(self): 8 """Reset the game's board to play again.""" 9 self._game.reset_game() 10 self._update_display(msg="Ready?") 11 for button in self._cells.keys(): 12 button.config(highlightbackground="lightblue") 13 button.config(text="") 14 button.config(fg="black")

This

.reset_board()

method works as follows:

  • Line 9 calls


    .reset_game()

    to reset the board’s abstract representation.

  • Line 10 updates the board display to hold the initial text,


    "Ready?"

    .

  • Line 11 starts a loop over the buttons on the board grid.

  • Lines 12 to 14 restore every button’s


    highlightbackground

    ,

    text

    , and

    fg

    properties to their initial state.

That’s it! With this last feature, your tic-tac-toe game project is complete. Go ahead and give it a try!

Next Steps

The tic-tac-toe game that you implemented in this tutorial is fairly bare-bones. However, you can expand it in several different and fun ways. Some ideas to take this game project to the next level include allowing your users to:

  • Use a different game board size
  • Play against the computer

What other ideas can you come up with to extend this project? Be creative and have fun!

Now that you’ve completed this project, here are some additional great projects to continue building your own games with Python:

  • Make Your First Python Game: Rock, Paper, Scissors!: In this tutorial, you’ll learn to program rock paper scissors in Python from scratch. You’ll learn how to take in user input, make the computer choose a random action, determine a winner, and split your code into functions.

  • PyGame: A Primer on Game Programming in Python: In this step-by-step tutorial, you’ll learn how to use PyGame. This library allows you to create games and rich multimedia programs in Python. You’ll learn how to draw items on your screen, implement collision detection, handle user input, and much more!

  • Build an Asteroids Game With Python and Pygame: This article will show you how to create a game in PyGame!

  • Arcade: A Primer on the Python Game Framework: This article is a excellent follow-up because it shows you another Python game framework that allows you to create more complex games.

  • Build a Platform Game in Python With Arcade: In this step-by-step tutorial, you’ll build a platform game in Python using the arcade library. You’ll cover techniques for designing levels, sourcing assets, and implementing advanced features.

  • Build a Tic-Tac-Toe Game Engine With an AI Player in Python: In this step-by-step tutorial, you’ll build a universal game engine in Python with tic-tac-toe rules and two computer players, including an unbeatable AI player using the minimax algorithm.

Lập trình Game bằng Python #2- Tạo Game cờ Caro (Tic Tac Toe) easy P1| Create Game Tic Tac Toe
Lập trình Game bằng Python #2- Tạo Game cờ Caro (Tic Tac Toe) easy P1| Create Game Tic Tac Toe

Step 3: Process the Players’ Moves on the Game’s Logic

In this tic-tac-toe game, you’ll mostly handle one type of event: players’ moves. Translated to Tkinter terms, a player’s move is just a click on the selected cell, which is represented by a button widget.

Every player’s move will trigger a bunch of operations on the

TicTacToeGame

class. These operations include:

  • Validating the move
  • Checking for a winner
  • Checking for a tied game
  • Toggling the player for the next move

In the following sections, you’ll write the code to handle all these operations in your

TicTacToeGame

class.

To download the source code for this step from GitHub, click the link below and navigate to the

source_code_step_3/

folder:

Get Source Code: Click here to get access to the source code that you’ll use to build your tic-tac-toe game.

Validate Players’ Moves

You need to validate the move every time a player clicks a given cell on the tic-tac-toe board. The question is: What defines a valid move? Well, at least two conditions make a move valid. Players can only play if:

  1. The game doesn’t have a winner.
  2. The selected move hasn’t already been played.

Go ahead and add the following method to the end of

TicTacToeGame

:


1# tic_tac_toe.py 2# ... 3 4class TicTacToeGame: 5 # ... 6 7 def is_valid_move(self, move): 8 """Return True if move is valid, and False otherwise.""" 9 row, col = move.row, move.col 10 move_was_not_played = self._current_moves[row][col].label == "" 11 no_winner = not self._has_winner 12 return no_winner and move_was_not_played

The

.is_valid_move()

method takes a

Move

object as an argument. Here’s what the rest of the method does:

  • Line 9 gets the


    .row

    and

    .col

    coordinates from the input

    move

    .

  • Line 10 checks if the move at the current coordinates,


    [row][col]

    , still holds an empty string as its label. This condition will be

    True

    if no player has made the input

    move

    before.

  • Line 11 checks if the game doesn’t have a winner yet.

This method returns a Boolean value that results from checking if the game has no winner and the current move hasn’t been played yet.

Process Players’ Moves to Find a Winner

Now it’s time for you to determine if a player has won the game after their last move. This may be your chief concern as the game designer. Of course, you’ll have many different ways to find out if a given player has won the game.

In this project, you’ll use the following ideas to determine the winner:

  • Every cell on the game board has an associated

    Move

    object.
  • Each

    Move

    object has a

    .label

    attribute that identifies the player who has made the move.

To find out if the last player has won the game, you’ll check if the player’s label is present in all the possible moves contained in a given winning combination.

Go ahead and add the following method to your

TicTacToeGame

class:


1# tic_tac_toe.py 2# ... 3 4class TicTacToeGame: 5 # ... 6 7 def process_move(self, move): 8 """Process the current move and check if it's a win.""" 9 row, col = move.row, move.col 10 self._current_moves[row][col] = move 11 for combo in self._winning_combos: 12 results = set( 13 self._current_moves[n][m].label 14 for n, m in combo 15 ) 16 is_win = (len(results) == 1) and ("" not in results) 17 if is_win: 18 self._has_winner = True 19 self.winner_combo = combo 20 break

Here’s a breakdown of what this new method does line by line:

  • Line 7 defines


    process_move()

    , which takes a

    Move

    object as an argument.

  • Line 9 gets the


    .row

    and

    .col

    coordinates from the input

    move

    .

  • Line 10 assigns the input


    move

    to the item at

    [row][col]

    in the list of current moves.

  • Line 11 starts a loop over the winning combinations.

  • Lines 12 to 15 run a generator expression that retrieves all the labels from the moves in the current winning combination. The result is then converted into a


    set

    object.

  • Line 16 defines a Boolean expression that checks if the current move determined a win or not. The result is stored in


    is_win

    .

  • Line 17 checks the content of


    is_win

    . If the variable holds

    True

    , then

    ._has_winner

    is set to

    True

    and

    .winner_combo

    is set to the current combination. Then the loop breaks and the function terminates.

On lines 12 to 16, a few points and ideas need clarification. To better understand lines 12 to 15, say that all the labels in the moves associated with the cells of the current winning combination hold an X. In that case, the generator expression will yield three X labels.

When you feed the built-in

set()

function with several instances of X, you get a set with a single instance of X. Sets don’t allow repeated values.

So, if the set in

results

contains a single value different from the empty string, then you have a winner. In this example, that winner would be the player with the X label. Line 16 checks both of these conditions.

To wrap up the topic of finding the winner of your tic-tac-toe game, go ahead and add the following method at the end of your

TicTacToeGame

class:


# tic_tac_toe.py # ... class TicTacToeGame: # ... def has_winner(self): """Return True if the game has a winner, and False otherwise.""" return self._has_winner

This method returns the Boolean value stored in

._has_winner

whenever you need to check if the current match has a winner or not. You’ll use this method later in this tutorial.

Check for Tied Games

In the tic-tac-toe game, if the players play on all the cells and there’s no winner, then the game is tied. So, you have two conditions to check before declaring the game as tied:

  1. All possible moves have been played.
  2. The game has no winner.

Go ahead and add the following method at the end of

TicTacToeGame

to check these conditions:


# tic_tac_toe.py # ... class TicTacToeGame: # ... def is_tied(self): """Return True if the game is tied, and False otherwise.""" no_winner = not self._has_winner played_moves = ( move.label for row in self._current_moves for move in row ) return no_winner and all(played_moves)

Inside

.is_tied()

, you first check if the game has no winner yet. Then you use the built-in

all()

function to check if all the moves in

._current_moves

have a label different from the empty string. If this is the case, then all the possible cells have already been played. If both conditions are true, then the game is tied.

Toggle Players Between Turns

Every time a player makes a valid move, you need to toggle the current player so that the other player can make the next move. To provide this functionality, go ahead and add the following method to your

TicTacToeGame

class:


# tic_tac_toe.py # ... class TicTacToeGame: # ... def toggle_player(self): """Return a toggled player.""" self.current_player = next(self._players)

Because

._players

holds an iterator that cyclically loops over the two default players, you can call

next()

on this iterator to get the next player whenever you need it. This toggling mechanism will allow the next player to take their turn and continue the game.

What We are building?

We will be implementing our Python knowledge learned so far from the scaler module link to Python module, to build, the project called the tic tac toe Python. Here we will be dividing the tic tac toe Python project into various steps to ease the understanding while parallelly building the game.

Tic tac toe Python, also known as Noughts and Crosses or Xs and Os, is a very simple two-player game where both the player get to choose any of the symbols between X and O. This game is played on a 3X3 grid board and one by one each player gets a chance to mark its respective symbol on the empty spaces of the grid. Once a player is successful in marking a strike of the same symbol either in the horizontal, vertical or diagonal way as shown in the picture below is created that player wins the game else the game goes on a draw if all the spots are filled.

Learn to Play tic tac toe Python

In the tic tac toe Python game that we shall be building, we require two players. These two players will be selecting their respective two signs which are generally used in the game that is, X and O. The two players draw the X and O on an alternative basis on the 3×3 grid having 9 empty boxes as shown below.

The game is played by drawing X and O in each box one by one for each player. The player who chose X starts the game. Once any player is successful in marking a strike of the same symbol either in the row-wise or column-wise or diagonally way as shown in the picture below is created that player wins the game else the game goes on a draw if all the spots are filled.

The players play the game as follows:

In total there are 8 ways to place the same sign to win the game. In the diagram below we can see all 8 arrangements.

When the 9 boxes get filled up without any winning arrangement then the game is said to be DRAW.

We can increase the complexity of the game by increasing the number of grids as well. We can create an automatic version of the game program as well which won’t require any input from the user. This would not take away the fun involved with the game and building the game from scratch would be a lot of fun too.

While implementing the interesting tic tac tow Python project we can use NumPy, pygame, or random Python libraries. With the below module, we shall be dividing the tic tac toe Python project into multiple steps to keep a parallel track of our game implementation alongside learning the concepts behind what we are doing and how we are implementing the project. We are not going to build those heavy games but we are building the tic tac toe Python project on the CLI or the command line interface.

Pre-requisites

The major topics that must be refreshed before creating and building the tic tac toe Python project are as follows:

  • Basic concepts of Python
  • User define functions in Python
  • Loops in Python (for loop, if else, if elif else)
  • try-exception block in Python
  • while loop of Python

How are we Going to Build the Tic Tac Toe Python Project?

The algorithm that we shall be following to build the tic tac toe Python project is as below:

  • We shall start by designing the tic tac toe Python grid for which we shall be using the command line interface as implementing tic tac toe in Python using CLI comes in handy. We shall be using the user-defined function and print statements in Python.
  • Then we shall be using the Data Structure to Store Data using the user-defined function in Python as it’s very important to understand the dynamics of the game. For this, we shall be knowing about two parts that are, The Status of the Grid and The move of each player.
  • After this we need to understand the game loop where we shall understand if the player has played their move without any exceptions.
  • Then we all implement the information about the game from time to time to record what is the status of the game.
  • It’s very important to mark out the win or lose situations for which we should be creating a user-defined function in Python and will be implementing if statements in Python to check if after every move the game has been won or tied by any player.
  • As this game is between two players our program needs to understand the same for we shall be using loops in Python to make this tic tac toe Python game give the player its chance alternatively.
  • In this step we shall be capturing the names of the player as we want our tic tac toe Python project to showcase a proper scorecard at the end of the game to display the name of the winner alongside.
  • After every move by the player we need to record the available chances the player holds to avoid any mismanagement by our tic tac toe Python project.
  • As we want to showcase the Winner of the game at the end, we will be recording the points earned by each player and creating a scoreboard around it we need to create that in this step.
  • We need our tic tac tor Python project to be flexible enough to allow the player to play as many matches as they want hence we shall be creating an outer loop of the game in this step.
  • After each alternative chance as we want our code to handle and store the selection of the current player we shall be using the try-exception block in Python to handle any exception if encountered for the selection of the player inputs.
  • The final step is to execute our entire program to help both the player play the game and record their victories too.

Final Output

The final project shall look like this where we can see the tic tac toe Python project after execution.

Output :

Python Tic Tac Toe Beginner Tutorial in PyGame | PART 1
Python Tic Tac Toe Beginner Tutorial in PyGame | PART 1

Tic Tac Toe

The tutorial is divided into three different sections. In the first section, you will get to know how to play the tic-tac-toe game. After that, we will see an algorithm that helps us to come up with the game logic. Finally, we will see the structured code and its explanation.

You may skip the first section if you already know how to play Tic Tac Toe.

So, without further ado, let’s dive into our first section.

Playing Tic Tac Toe

There will be two players in a game. Two signs represent each player. The general signs used in the game are X and O. Finally, there will be a board with 9 boxes.

See the tic-tac-toe board visually.

The gameplay will be as follows.

  • First, one user will place their sign in one of the available empty boxes.
  • Next, the second user will place their sign in one of the available empty boxes.
  • The goal of the players is to place their respective signs completely row-wise or column-wise, or diagonally.
  • The game goes on until a player wins the game or it ended up in a draw by filling all boxes without a winning match.

Let’s see some gameplays visually.

The player X wins the game in the above gameplay. All boxes diagonally fill with X signs. So, the respective player wins the game.

There are a total of 8 ways to arrange the same sign and win the game. Let’s see all the 8 arrangements that can win the game.

And finally, a draw fills the board without any winning arrangement. I hope you understand how to Tic Tac Toe now.

Now, it’s playtime for you. You may go here and play it to understand the gameplay completely. Leave it if you have already got it.

Now, it’s time to move the algorithm section.

Algorithm

We will now discuss the algorithm to write the code. This algorithm will help you to write code in any programming language of your choice. Let’s see how it’s done.

  • Create a board using a 2-dimensional array and initialize each element as empty.

    • You can represent empty using any symbol you like. Here, we are going to use a hyphen.

      '-'

      .
  • You can represent empty using any symbol you like. Here, we are going to use a hyphen.
  • Write a function to check whether the board is filled or not.

    • Iterate over the board and return

      false

      if the board contains an empty sign or else return

      true

      .
  • Iterate over the board and return
  • Write a function to check whether a player has won or not.

    • We have to check all the possibilities that we discussed in the previous section.
    • Check for all the rows, columns, and two diagonals.
  • Write a function to show the board as we will show the board multiple times to the users while they are playing.
  • Write a function to start the game.

    • Select the first turn of the player randomly.
    • Write an infinite loop that breaks when the game is over (either win or draw).

      • Show the board to the user to select the spot for the next move.
      • Ask the user to enter the row and column number.
      • Update the spot with the respective player sign.
      • Check whether the current player won the game or not.
      • If the current player won the game, then print a winning message and break the infinite loop.
      • Next, check whether the board is filled or not.
      • If the board is filled, then print the draw message and break the infinite loop.
    • Finally, show the user the final view of the board.

You may be able to visualize what’s happening. Don’t worry, even if you didn’t understand it completely. You will get more clarity once you see the code.

So, let’s jump into the code section. I assume you have Python installed on your PC to try the code.

Code

Go through the below code.


import random class TicTacToe: def __init__(self): self.board = [] def create_board(self): for i in range(3): row = [] for j in range(3): row.append('-') self.board.append(row) def get_random_first_player(self): return random.randint(0, 1) def fix_spot(self, row, col, player): self.board[row][col] = player def is_player_win(self, player): win = None n = len(self.board) # checking rows for i in range(n): win = True for j in range(n): if self.board[i][j] != player: win = False break if win: return win # checking columns for i in range(n): win = True for j in range(n): if self.board[j][i] != player: win = False break if win: return win # checking diagonals win = True for i in range(n): if self.board[i][i] != player: win = False break if win: return win win = True for i in range(n): if self.board[i][n - 1 - i] != player: win = False break if win: return win return False for row in self.board: for item in row: if item == '-': return False return True def is_board_filled(self): for row in self.board: for item in row: if item == '-': return False return True def swap_player_turn(self, player): return 'X' if player == 'O' else 'O' def show_board(self): for row in self.board: for item in row: print(item, end=" ") print() def start(self): self.create_board() player = 'X' if self.get_random_first_player() == 1 else 'O' while True: print(f"Player {player} turn") self.show_board() # taking user input row, col = list( map(int, input("Enter row and column numbers to fix spot: ").split())) print() # fixing the spot self.fix_spot(row - 1, col - 1, player) # checking whether current player is won or not if self.is_player_win(player): print(f"Player {player} wins the game!") break # checking whether the game is draw or not if self.is_board_filled(): print("Match Draw!") break # swapping the turn player = self.swap_player_turn(player) # showing the final view of board print() self.show_board() # starting the game tic_tac_toe = TicTacToe() tic_tac_toe.start()

Check out the sample output of the code.


$ python tic_tac_toe.py Player X turn - - - - - - - - - Enter row and column numbers to fix spot: 1 1 Player O turn X - - - - - - - - Enter row and column numbers to fix spot: 2 1 Player X turn X - - O - - - - - Enter row and column numbers to fix spot: 1 2 Player O turn X X - O - - - - - Enter row and column numbers to fix spot: 1 3 Player X turn X X O O - - - - - Enter row and column numbers to fix spot: 2 2 Player O turn X X O O X - - - - Enter row and column numbers to fix spot: 3 3 Player X turn X X O O X - - - O Enter row and column numbers to fix spot: 3 2 Player X wins the game! X X O O X - - X O

Some major points that help you understand the structure of the code.

  • We have used a class to have all the methods in one place. It can easily be a reusable bundle in some other code as well.
  • Next, we have defined different functions for each responsibility, even if it is a small task. It helps to maintain the code with ease.
  • The above two approaches help us update the app effortlessly if we want to update the game.

Feel free to adapt the structure and improve it based on your project. Structuring the code is not limited.

Final Words

Hurray! 😎 You have created a game completely from scratch. It is not one of the visual games that we play daily. But it helps you to write logic and maintain clean structure in code. Follow similar guidelines to create some interesting games like this. You can find similar games if you go back some years to your childhood.

Happy Coding! 👩💻

Next, explore how to create number guessing game and Unit Testing with Python unittest Module.

Star

You must be signed in to star a gist

A traditional Tic Tac Toe game written in Python

# Pam Qian 2016 Fall CS 112 Python Midterm Project II
# Tic Tack Toe
def main():
# The main function
introduction = intro()
board = create_grid()
pretty = printPretty(board)
symbol_1, symbol_2 = sym()
full = isFull(board, symbol_1, symbol_2) # The function that starts the game is also in here.
def intro():
# This function introduces the rules of the game Tic Tac Toe
print(“Hello! Welcome to Pam’s Tic Tac Toe game!”)
print(“\n”)
print(“Rules: Player 1 and player 2, represented by X and O, take turns ”
“marking the spaces in a 3*3 grid. The player who succeeds in placing ”
“three of their marks in a horizontal, vertical, or diagonal row wins.”)
print(“\n”)
input(“Press enter to continue.”)
print(“\n”)
def create_grid():
# This function creates a blank playboard
print(“Here is the playboard: “)
board = [[” “, ” “, ” “],
[” “, ” “, ” “],
[” “, ” “, ” “]]
return board
def sym():
# This function decides the players’ symbols
symbol_1 = input(“Player 1, do you want to be X or O? “)
if symbol_1 == “X”:
symbol_2 = “O”
print(“Player 2, you are O. “)
else:
symbol_2 = “X”
print(“Player 2, you are X. “)
input(“Press enter to continue.”)
print(“\n”)
return (symbol_1, symbol_2)
def startGamming(board, symbol_1, symbol_2, count):
# This function starts the game.
# Decides the turn
if count % 2 == 0:
player = symbol_1
elif count % 2 == 1:
player = symbol_2
print(“Player “+ player + “, it is your turn. “)
row = int(input(“Pick a row:”
“[upper row: enter 0, middle row: enter 1, bottom row: enter 2]:”))
column = int(input(“Pick a column:”
“[left column: enter 0, middle column: enter 1, right column enter 2]”))
# Check if players’ selection is out of range
while (row > 2 or row < 0) or (column > 2 or column < 0):
outOfBoard(row, column)
row = int(input(“Pick a row[upper row:”
“[enter 0, middle row: enter 1, bottom row: enter 2]:”))
column = int(input(“Pick a column:”
“[left column: enter 0, middle column: enter 1, right column enter 2]”))
# Check if the square is already filled
while (board[row][column] == symbol_1)or (board[row][column] == symbol_2):
filled = illegal(board, symbol_1, symbol_2, row, column)
row = int(input(“Pick a row[upper row:”
“[enter 0, middle row: enter 1, bottom row: enter 2]:”))
column = int(input(“Pick a column:”
“[left column: enter 0, middle column: enter 1, right column enter 2]”))
# Locates player’s symbol on the board
if player == symbol_1:
board[row][column] = symbol_1
else:
board[row][column] = symbol_2
return (board)
def isFull(board, symbol_1, symbol_2):
count = 1
winner = True
# This function check if the board is full
while count < 10 and winner == True:
gaming = startGamming(board, symbol_1, symbol_2, count)
pretty = printPretty(board)
if count == 9:
print(“The board is full. Game over.”)
if winner == True:
print(“There is a tie. “)
# Check if here is a winner
winner = isWinner(board, symbol_1, symbol_2, count)
count += 1
if winner == False:
print(“Game over.”)
# This is function gives a report
report(count, winner, symbol_1, symbol_2)
def outOfBoard(row, column):
# This function tells the players that their selection is out of range
print(“Out of boarder. Pick another one. “)
def printPretty(board):
# This function prints the board nice!
rows = len(board)
cols = len(board)
print(“—+—+—“)
for r in range(rows):
print(board[r][0], ” |”, board[r][1], “|”, board[r][2])
print(“—+—+—“)
return board
def isWinner(board, symbol_1, symbol_2, count):
# This function checks if any winner is winning
winner = True
# Check the rows
for row in range (0, 3):
if (board[row][0] == board[row][1] == board[row][2] == symbol_1):
winner = False
print(“Player ” + symbol_1 + “, you won!”)
elif (board[row][0] == board[row][1] == board[row][2] == symbol_2):
winner = False
print(“Player ” + symbol_2 + “, you won!”)
# Check the columns
for col in range (0, 3):
if (board[0][col] == board[1][col] == board[2][col] == symbol_1):
winner = False
print(“Player ” + symbol_1 + “, you won!”)
elif (board[0][col] == board[1][col] == board[2][col] == symbol_2):
winner = False
print(“Player ” + symbol_2 + “, you won!”)
# Check the diagnoals
if board[0][0] == board[1][1] == board[2][2] == symbol_1:
winner = False
print(“Player ” + symbol_1 + “, you won!”)
elif board[0][0] == board[1][1] == board[2][2] == symbol_2:
winner = False
print(“Player ” + symbol_2 + “, you won!”)
elif board[0][2] == board[1][1] == board[2][0] == symbol_1:
winner = False
print(“Player ” + symbol_1 + “, you won!”)
elif board[0][2] == board[1][1] == board[2][0] == symbol_2:
winner = False
print(“Player ” + symbol_2 + “, you won!”)
return winner
def illegal(board, symbol_1, symbol_2, row, column):
print(“The square you picked is already filled. Pick another one.”)
def report(count, winner, symbol_1, symbol_2):
print(“\n”)
input(“Press enter to see the game summary. “)
if (winner == False) and (count % 2 == 1 ):
print(“Winner : Player ” + symbol_1 + “.”)
elif (winner == False) and (count % 2 == 0 ):
print(“Winner : Player ” + symbol_2 + “.”)
else:
print(“There is a tie. “)
# Call Main
main()

adityapandey141
commented
Feb 3, 2023

creating this simple 2-player tic-tac-toe game using pythonhttps://ohastech.com/tic-tac-toe-game-with-python-tkinter-gui/

jarvissilva937
commented
Nov 1, 2023

Great code, here is is tutorial to make fruit ninja game in python

Incerivers
commented
Jan 13, 2024

@basket random Thank you for providing the useful code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment


import


numpy as np


import


random


from


time


import


sleep


def


create_board():


return


(np.array([[


],


],


]]))


def


possibilities(board):


[]


for


in


range


len


(board)):


for


in


range


len


(board)):


if


board[i][j]


l.append((i, j))


return


(l)


def


random_place(board, player):


selection


possibilities(board)


current_loc


random.choice(selection)


board[current_loc]


player


return


(board)


def


row_win(board, player):


for


in


range


len


(board)):


win


True


for


in


range


len


(board)):


if


board[x, y] !


player:


win


False


continue


if


win


True


return


(win)


return


(win)


def


col_win(board, player):


for


in


range


len


(board)):


win


True


for


in


range


len


(board)):


if


board[y][x] !


player:


win


False


continue


if


win


True


return


(win)


return


(win)


def


diag_win(board, player):


win


True


for


in


range


len


(board)):


if


board[x, x] !


player:


win


False


if


win:


return


win


win


True


if


win:


for


in


range


len


(board)):


len


(board)


if


board[x, y] !


player:


win


False


return


win


def


evaluate(board):


winner


for


player


in


]:


if


(row_win(board, player)


or


col_win(board, player)


or


diag_win(board, player)):


winner


player


if


np.


all


(board !


and


winner


winner


return


winner


def


play_game():


board, winner, counter


create_board(),


print


(board)


sleep(


while


winner


for


player


in


]:


board


random_place(board, player)


print


"Board after "


str


(counter)


" move"


print


(board)


sleep(


counter


winner


evaluate(board)


if


winner !


break


return


(winner)


print


"Winner is: "


str


(play_game()))

Tic Tac Toe Python

Step 2: Set Up the Tic-Tac-Toe Game Logic in Python

Up to this point, you’ve put together a suitable tic-tac-toe game board using Tkinter. Now you need to think of how to deal with the game’s logic. This logic will consist of code that processes a player’s move and determines if this player has won the game or not.

Several ideas are key when it comes to implementing the logic of a tic-tac-toe game. First, you need a valid representation of the players and their moves. You also need a higher-level class to represent the game itself. In this section, you’ll define classes for these three logic concepts.

You can download the source code for this step by clicking the link below and navigating to the

source_code_step_2/

folder:

Get Source Code: Click here to get access to the source code that you’ll use to build your tic-tac-toe game.

Define Classes for the Players and Their Moves

In the first round, you’ll define classes to represent players and their moves on the game board. These classes will be pretty bare-bones. All they need is a few attributes each. They don’t even need to have any methods.

You can use a few tools to build classes that fulfill these requirements. For example, you can use either a data class or a named tuple. In this tutorial, you’ll use a named tuple for both classes because this kind of class provides all you need.

Instead of using the classic

namedtuple

from the

collections

module, you’ll use the

NamedTuple

class from

typing

as a way to provide initial type hint information in your classes.

Go back to your code editor and add the following code at the beginning of your

tic_tac_toe.py

file:


1# tic_tac_toe.py 2 3import tkinter as tk 4from tkinter import font 5from typing import NamedTuple 6 7class Player(NamedTuple): 8 label: str 9 color: str 10 11class Move(NamedTuple): 12 row: int 13 col: int 14 label: str = "" 15 16# ...

Here’s a breakdown of this code snippet:

  • Line 5 imports


    NamedTuple

    from

    typing

    .

  • Lines 7 to 9 define the


    Player

    class. The

    .label

    attribute will store the classic player signs, X and O. The

    .color

    attribute will hold a string with a Tkinter color. You’ll use this color to identify the target player on the game board.

  • Lines 11 to 14 define the


    Move

    class. The

    .row

    and

    .col

    attributes will hold the coordinates that identify the move’s target cell. The

    .label

    attribute will hold the sign that identifies the player, X or O. Note that

    .label

    defaults to the empty string,

    ""

    , which means that this specific move hasn’t been played yet.

With these two classes in place, now you can define the class that you’ll use to represent the game logic.

Create a Class to Represent the Game Logic

In this section, you’ll define a class to manage the game’s logic. This class will take care of processing the moves, finding a winner, toggling players, and performing a few other tasks. Get back to your

tic_tac_toe.py

file and add the following class right before your

TicTacToeBoard

class:


# tic_tac_toe.py import tkinter as tk from itertools import cycle from tkinter import font # ... class TicTacToeGame: def __init__(self, players=DEFAULT_PLAYERS, board_size=BOARD_SIZE): self._players = cycle(players) self.board_size = board_size self.current_player = next(self._players) self.winner_combo = [] self._current_moves = [] self._has_winner = False self._winning_combos = [] self._setup_board() class TicTacToeBoard(tk.Tk): # ...

Here, you first import

cycle()

from the

itertools

module. Then you define

TicTacToeGame

, whose initializer takes two arguments,

players

and

board_size

. The

players

argument will hold a tuple of two

Player

objects, representing players X and O. This argument defaults to

DEFAULT_PLAYERS

, a constant that you’ll define in a moment.

The

board_size

argument will hold a number representing the size of the game board. In a classic tic-tac-toe game, this size would be . In your class, the argument defaults to

BOARD_SIZE

, another constant that you’ll define soon.

Inside

.__init__()

, you define the following instance attributes:

Attribute Description
A cyclical iterator over the input tuple of
The board size
The current player
The combination of cells that defines a winner
The list of players’ moves in a given game
A Boolean variable to determine if the game has a winner or not
A list containing the cell combinations that define a win

The

._players

attribute calls

cycle()

from the

itertools

module. This function takes an iterable as an argument and returns an iterator that cyclically yields items from the input iterable. In this case, the argument to

cycle()

is the tuple of default players passed in through the

players

argument. As you go through this tutorial, you’ll learn more about all the attributes in the above table.

Regarding the last line in

.__init__()

, it calls

._setup_board()

, which is a method that you’ll also define in a moment.

Now go ahead and define the following constants right below the

Move

class:


# tic_tac_toe.py # ... class Move(NamedTuple): # ... BOARD_SIZE = 3 DEFAULT_PLAYERS = ( Player(label="X", color="blue"), Player(label="O", color="green"), ) class TicTacToeGame: # ...

As you already learned,

BOARD_SIZE

holds the size of the tic-tac-toe board. Typically, this size is . So, you’ll have a three-by-three grid of cells on the board.

On the other hand,

DEFAULT_PLAYERS

defines a two-item tuple. Each item represents a player in the game. The

.label

and

.color

attributes of each player are set to suitable values. Player X will be blue, and player O will be green.

Set Up the Abstract Game Board

Managing the game’s state in every moment is a fundamental step in the game’s logic. You need to keep track of every move on the board. To do this, you’ll use the

._current_moves

attribute, which you’ll update whenever a player makes a move.

You also need to determine which cell combinations on the board determine a win. You’ll store these combinations in the

._winning_combos

attribute.

Here’s the

._setup_board()

method, which computes initial values for

._current_moves

and

._winning_combos

:


# tic_tac_toe.py # ... class TicTacToeGame: # ... def _setup_board(self): self._current_moves = [ [Move(row, col) for col in range(self.board_size)] for row in range(self.board_size) ] self._winning_combos = self._get_winning_combos()

In

._setup_board()

, you use a list comprehension to provide an initial list of values for

._current_moves

. The comprehension creates a list of lists. Each inner list will contain empty

Move

objects. An empty move stores the coordinates of its containing cell and an empty string as the initial player’s label.

The last line of this method calls

._get_winning_combos()

and assigns its return value to

._winning_combos

. You’ll implement this new method in the following section.

Figure Out the Winning Combinations

On a classic tic-tac-toe board, you’ll have eight possible winning combinations. They’re essentially the rows, columns, and diagonals of the board. The following illustration shows these winning combinations:

How would you get the coordinates of all these combinations using Python code? There are several ways to do it. In the code below, you’ll use four list comprehensions to get all the possible winning combinations:


# tic_tac_toe.py # ... class TicTacToeGame: # ... def _get_winning_combos(self): rows = [ [(move.row, move.col) for move in row] for row in self._current_moves ] columns = [list(col) for col in zip(*rows)] first_diagonal = [row[i] for i, row in enumerate(rows)] second_diagonal = [col[j] for j, col in enumerate(reversed(columns))] return rows + columns + [first_diagonal, second_diagonal]

The main input for this method is the

._current_moves

attribute. By default, this attribute will hold a list containing three sublists. Each sublist will represent a row on the grid and have three

Move

objects in it.

The first comprehension iterates over the rows on the grid, getting the coordinates of every cell and building a sublist of coordinates. Each sublist of coordinates represents a winning combination. The second comprehension creates sublists containing the coordinates of each cell in the grid columns.

The third and fourth comprehensions use a similar approach to get the coordinates of every cell in the board diagonals. Finally, the method returns a list of lists containing all possible winning combinations on the tic-tac-toe board.

With this initial setup for your game board, you’re ready to start thinking about processing the players’ moves.

Python Project: Tic Tac Toe Game in Python 🔥
Python Project: Tic Tac Toe Game in Python 🔥

Step 4: Process Players’ Moves on the Game Board

At this point, you’re able to handle the players’ moves on the game logic. Now you have to connect this logic to the game board itself. You also need to write the code to make the board respond to players’ moves.

First, go ahead and inject the game logic into the game board. To do this, update the

TicTacToeBoard

class as in the code below:


# tic_tac_toe.py # ... class TicTacToeGame: # ... class TicTacToeBoard(tk.Tk): def __init__(self, game): super().__init__() self.title("Tic-Tac-Toe Game") self._cells = {} self._game = game self._create_board_display() self._create_board_grid() # ... def _create_board_grid(self): grid_frame = tk.Frame(master=self) grid_frame.pack() for row in range(self._game.board_size): self.rowconfigure(row, weight=1, minsize=50) self.columnconfigure(row, weight=1, minsize=75) for col in range(self._game.board_size): # ...

In this code snippet, you first add a

game

argument to the

TicTacToeBoard

initializer. Then you assign this argument to an instance attribute,

._game

, which will give you full access to the game logic from the game board.

The second update is to use

._game.board_size

to set the board size instead of using a magic number. This update also enables you to use different board sizes. For example, you can create a four-by-four board grid, which can be an exciting experience.

With these updates, you’re ready to dive into handling the players’ moves on the

TicTacToeBoard

class.

As usual, you can download the source code for this step by clicking the link below and navigating to the

source_code_step_4/

folder:

Get Source Code: Click here to get access to the source code that you’ll use to build your tic-tac-toe game.

Handle a Player’s Move Event

The

.mainloop()

method on the

Tk

class runs what’s known as the application’s main loop or event loop. This is an infinite loop in which all the GUI events happen. Inside this loop, you can handle the events on the application’s user interface. An event is a user action on the GUI, such as a keypress, mouse move, or mouse click.

When a player in your tic-tac-toe game clicks a cell, a click event occurs inside the game’s event loop. You can process this event by providing an appropriate handler method on your

TicTacToeBoard

class. To do this, get back to your code editor and add the following

.play()

method at the end of the class:


1# tic_tac_toe.py 2# ... 3 4class TicTacToeBoard(tk.Tk): 5 # ... 6 7 def play(self, event): 8 """Handle a player's move.""" 9 clicked_btn = event.widget 10 row, col = self._cells[clicked_btn] 11 move = Move(row, col, self._game.current_player.label) 12 if self._game.is_valid_move(move): 13 self._update_button(clicked_btn) 14 self._game.process_move(move) 15 if self._game.is_tied(): 16 self._update_display(msg="Tied game!", color="red") 17 elif self._game.has_winner(): 18 self._highlight_cells() 19 msg = f'Player "{self._game.current_player.label}" won!' 20 color = self._game.current_player.color 21 self._update_display(msg, color) 22 else: 23 self._game.toggle_player() 24 msg = f"{self._game.current_player.label}'s turn" 25 self._update_display(msg)

This method is fundamental in your tic-tac-toe game because it puts together almost all the game logic and GUI behavior. Here’s a summary of what this method does:

  • Line 7 defines


    play()

    , which takes a Tkinter event object as an argument.

  • Line 9 retrieves the widget that triggered the current event. This widget will be one of the buttons on the board grid.

  • Line 10 unpacks the button’s coordinates into two local variables,


    row

    and

    col

    .

  • Line 11 creates a new


    Move

    object using

    row

    ,

    col

    , and the current player’s

    .label

    attribute as arguments.

  • Line 12 starts a conditional statement that checks if the player’s move is valid or not. If the move is valid, then the


    if

    code block runs. Otherwise, no further action takes place.

  • Line 13 updates the clicked button by calling the


    ._update_button()

    method. You’ll write this method in the next section. In short, the method updates the button’s text to reflect the current player’s label and color.

  • Line 14 calls


    .process_move()

    on the

    ._game

    object using the current move as an argument.

  • Line 15 checks if the game is tied. If that’s the case, then the game display gets updated accordingly.

  • Line 17 checks if the current player has won the game. Then line 18 highlights the winning cells, and lines 19 to 21 update the game display to acknowledge the winner.

  • Line 22 runs if the game isn’t tied and there’s no winner. In this case, lines 23 to 25 toggle the player for the next move and update the display to point out the player who will play next.

You’re almost there! With a few more updates and additions, your tic-tac-toe game will be ready for its first-ever match.

The next step is to connect every button on the game board to the

.play()

method. To do this, get back to the

._create_board_grid()

method and update it as in the code below:


# tic_tac_toe.py # ... class TicTacToeBoard(tk.Tk): # ... def _create_board_grid(self): grid_frame = tk.Frame(master=self) grid_frame.pack() for row in range(self._game.board_size): self.rowconfigure(row, weight=1, minsize=50) self.columnconfigure(row, weight=1, minsize=75) for col in range(self._game.board_size): # ... self._cells[button] = (row, col) button.bind("

", self.play) # ...

The highlighted line binds the click event of every button on the game board with the

.play()

method. This way, whenever a player clicks a given button, the method will run to process the move and update the game state.

Update the Game Board to Reflect the Game State

To complete the code for processing the players’ moves on the game board, you need to write three helper methods. These methods will complete the following actions:

  • Update the clicked button
  • Update the game display
  • Highlight the winning cells

To kick things off, go ahead and add

._update_button()

to

TicTacToeBoard

:


# tic_tac_toe.py # ... class TicTacToeBoard(tk.Tk): # ... def _update_button(self, clicked_btn): clicked_btn.config(text=self._game.current_player.label) clicked_btn.config(fg=self._game.current_player.color)

In this code snippet,

._update_button()

calls

.config()

on the clicked button to set its

.text

attribute to the current player’s label. The method also sets the text foreground color,

fg

, to the current player’s color.

The next helper method to add is

._update_display()

:


# tic_tac_toe.py # ... class TicTacToeBoard(tk.Tk): # ... def _update_display(self, msg, color="black"): self.display["text"] = msg self.display["fg"] = color

In this method, instead of using

.config()

to tweak the text and color of the game display, you use a dictionary-style subscript notation. Using this type of notation is another option that Tkinter provides for accessing a widget’s attributes.

Finally, you need a helper method to highlight the winning cells once a given player makes a winning move:


# tic_tac_toe.py # ... class TicTacToeBoard(tk.Tk): # ... def _highlight_cells(self): for button, coordinates in self._cells.items(): if coordinates in self._game.winner_combo: button.config(highlightbackground="red")

The loop inside

._highlight_cells()

iterates over the items in the

._cells

dictionary. This dictionary maps buttons to their row and column coordinates on the board grid. If the current coordinates are in a winning cell combination, then the button’s background color is set to

"red"

, highlighting the cell combination on the board.

With this last helper method in place, your tic-tac-toe game is ready for the first match!

Run Your Tic-Tac-Toe Game for the First Time

To finish putting together the logic and the user interface of your tic-tac-toe game, you need to update the game’s

main()

function. Up to this point, you have a

TicTacToeBoard

object only. You need to create a

TicTacToeGame

object and pass it over to the

TicTacToeBoard

updated constructor.

Get back to

main()

and update it like in the code below:


# tic_tac_toe.py # ... def main(): """Create the game's board and run its main loop.""" game = TicTacToeGame() board = TicTacToeBoard(game) board.mainloop()

In this code, the first highlighted line creates an instance of

TicTacToeGame

, which you’ll use to handle the game logic. The second highlighted line passes the new instance to the

TicTacToeBoard

class constructor, which injects the game logic into the game board.

With these updates in place, you can now run your game. To do this, fire up a terminal window and navigate to the directory containing your

tic_tac_toe.py

file. Then run the following command:


$ python tic_tac_toe.py

Once this command has run, then your game’s main window will appear on your screen. Go ahead and give it a try! It’ll behave something like this:

Wow! Your game project looks amazing so far! It allows two players to share their mouse and play a classic tic-tac-toe match. The game GUI looks nice and, in general, the game works as expected.

In the following section, you’ll write code to allow the players to restart the game and play again. You’ll also provide the option of exiting the game.

Introduction

In this article, I am showing you how to create a very simple game of Tic-Tac-Toe in Python.

Tic-Tac-Toe is a very simple two-player game. So only two players can play at a time. This game is also known as Noughts and Crosses or Xs and Os game. One player plays with X, and the other player plays with O. In this game, we have a board consisting of a 3X3 grid. The number of grids may be increased.

The Tic-Tac-Toe board looks like the following

How To Code Tic Tac Toe With Python | Programming Tutorial For Beginners
How To Code Tic Tac Toe With Python | Programming Tutorial For Beginners

Condition for wiining

Whoever places three respective marks (X or O) horizontally, vertically, or diagonally will be the winner.

The code for the game is as follows.


import os
import time
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
player = 1
# Win Flags
Win = 1
Draw = -1
Running = 0
Stop = 1
Game = Running
Mark = 'X'
def DrawBoard():
print(" %c | %c | %c " % (board[1], board[2], board[3]))
print("___|___|___")
print(" %c | %c | %c " % (board[4], board[5], board[6]))
print("___|___|___")
print(" %c | %c | %c " % (board[7], board[8], board[9]))
print(" | | ")
def CheckPosition(x):
if board[x] == ' ':
return True
else:
return False
def CheckWin():
global Game
if board[1] == board[2] and board[2] == board[3] and board[1] != ' ':
Game = Win
elif board[4] == board[5] and board[5] == board[6] and board[4] != ' ':
Game = Win
elif board[7] == board[8] and board[8] == board[9] and board[7] != ' ':
Game = Win
elif board[1] == board[4] and board[4] == board[7] and board[1] != ' ':
Game = Win
elif board[2] == board[5] and board[5] == board[8] and board[2] != ' ':
Game = Win
elif board[3] == board[6] and board[6] == board[9] and board[3] != ' ':
Game = Win
elif board[1] == board[5] and board[5] == board[9] and board[5] != ' ':
Game = Win
elif board[3] == board[5] and board[5] == board[7] and board[5] != ' ':
Game = Win
elif board[1] != ' ' and board[2] != ' ' and board[3] != ' ' and \
board[4] != ' ' and board[5] != ' ' and board[6] != ' ' and \
board[7] != ' ' and board[8] != ' ' and board[9] != ' ':
Game = Draw
else:
Game = Running
print("Tic-Tac-Toe Game Designed By Sourabh Somani")
print("Player 1 [X] --- Player 2 [O]\n")
print()
print()
print("Please Wait...")
time.sleep(3)
while Game == Running:
os.system('cls')
DrawBoard()
if player % 2 != 0:
print("Player 1's chance")
Mark = 'X'
else:
print("Player 2's chance")
Mark = 'O'
choice = int(input("Enter the position between [1-9] where you want to mark: "))
if CheckPosition(choice):
board[choice] = Mark
player += 1
CheckWin()
os.system('cls')
DrawBoard()
if Game == Draw:
print("Game Draw")
elif Game == Win:
player -= 1
if player % 2 != 0:
print("Player 1 Won")
else:
print("Player 2 Won")

Output

How to Create a Tic-Tac-Toe Game in Python?

Let us create a simple Tic Tac Toe game in Python. It will help you to build up game logic and understand how to structure code.

Gaming is one of the entertainment that humans have. We can find different types of games on the web, mobile, desktop, etc. We are not here to make one of those heavy games now. We are going to create a CLI tic-tac-toe game using Python.

If you are not familiar with Tic Tac Toe, play it visually here to understand. Don’t worry, even if you don’t understand it, we are going to see it.

Building Tic Tac Toe using Python

Now after understanding the logical flow of the project and refreshing our Python knowledge based on the pre-requisite, let us start to create our tic tac toe Python project step by step.

Step 1: Designing the Tic Tac Toe Python Project:

As discussed in the algorithm before we can start playing the game as we are building our tic tac tor Python game from scratch that too using the command line interface. We need to start by designing a tic tac toe Python program 3X3 gameboard. For doing so, we shall be using the print statements from Python and designing the 9 empty boxes of the game board.

Our prime objective in creating the design of the tic tac toe Python grid function would be that whenever a player needs to mark the box of their choice, then he/she will be inputting the respective digit that is displayed on the grid. For example, if we want to select the first box of the grid on the leftmost corner then we will input 1 in the command line interface.

Code :

Output :

Explanation :

As seen above, we created a function called tictactoe_grid where we implemented the user-defined function knowledge from Python. This function takes values from the user as its parameter. We have used the print function along with the format function to act as the placeholder for the user’s input value. Here the value parameter, signifies the status of each cell of the grid as a list.

Step 2: Using the Data Structure to Store Data

Now to understand the key principles of any game we need to dive deep into the dynamics of that game.

As we are building a relatively simple game, we need to know two important pieces of information that need to be stored so that they can be referred to at any point in time during the game which is as follow:

The Status of Grid: For this we will create a data structure that stores the status for each cell which can be either filled or empty.

The Move of each player: it is always good to store the past and present moves of each player which are the positions occupied by ‘X’ and ‘O’.

Quick Note: We can access the above data from the Status of Grid which requires us to pass over the information every time we need to know the positions of each player. This is generally done by conserving time via the Time versus Space Complexity Trade-off.

Code :

Output :

Explanation :

As seen above, we created a user-defined function game_single for the tic-tac-toe Python game. This function is created for a single game of tic tac toe Python where the value signifies the parameter of the previous function. The variable position_player is used for storing the position of the box that is either filled by the cross (X) or the naught (O). We store three values that help to manage the Grid Status as a list of characters:

‘X’ – This signifies when a cell is occupied by the X Player. ‘O’ – This signifies when a cell is occupied by the O Player. ‘ ‘ – This signifies when a cell is empty or vacant.

To check the player move, we have created the variable position_player where the moves of the players are stored as a dictionary (consisting of a list of integers) where the keys are defined by ‘X’ and ‘O’ for each player.

Quick Note: The player_current variable is used to store the move of the current player as ‘X’ or ‘O’.

Step 3: To Understand the Game-Loop

Understanding the game loop for the tic tac toe Python game allows the player to understand how to play the game until that player wins or a draw happens between the two players. Also, in the tic tac toe Python game, every single move of the player is denoted by the loop iteration.

Code :

Explanation :

To print the values for the function tictactoe_grid(), we have made use of the while loop from Python that helps us to generate the single tic tac toe Python game loop.

To handle the input from the player, we are using the Try-Exception block for ‘CHANCE’ input that can handle the unintended value if provided by the payer as his move during each iteration of the game. We also handled the ValueError exception to resolve if the same error gets encountered and also to maintain the continuity of the game. Finally, we also performed a few sanity checks, to verify if the value given by the player is a valid input or not or if the valid position given is already occupied or not.

Step 4: Updating the Game Information

Now that we have understood the game loop and gathered the inputs from the player, we need to update the information too. We can make our tic tac toe Python game work smoothly by updating the information by concatenating the below-given piece of code into our main game program.

Code :

Output :

Explanation :

Once we call our tictactoe_grid() function, the grid will be as shown above as we now have the value list updated. We updated the status of the grid in addition to the position of the player by updating our game information where we update the boxes that got occupied as per the players which are reflected by the value list. Also, by adding the position just filed by the move of the current player we reflect the position of the player.

Step 5: To Validate the Win or Tie Situation

Now we move towards analyzing the win or tie situation. For that, we need to validate if any player after every move it takes has won the tic tac toe Python game or if the game ended as a tie.

We will be creating two user-defined functions in Python to validate the Win or Tie situation. We name these functions win_validate() and tie_validate().

win_validate(): This function validates if the player has satisfied any of the winning combinations that are stored. If it does, then it shall return TRUE; otherwise, it shall give output as FALSE.

tie_validate(): This is a function that validates if all ‘Nine’ boxes on the grid are filled and the game is ending with a tie.

Code :

Explanation :

As seen above, we created user-defined function (UDF) in Python to define the win_validate() and tie_validate(). We made use of the for loops in Python and if statements to validate if the winning combination to win the game is met or not. Consecutively, while calling both the functions we shall get the respective output if the game is won by any player or it has resulted in a tie. The game_single() function shall return if the current player has won the game or not. Else, the game will return ‘D’ signifying a tie.

Step 6: Switching Between the Player Once the Chance of One Player is Executed

As the tic tac toe Python game is based on an alternate chance being given to each player after one player has played its chance therefore we shall be using the if-else loop in Python now to enable this switching between the players after its chance has been executed.

Code :

Explanation :

We implemented the if-else statement in Python to switch between the player once the chance of one player is executed in a way that when the current player makes its move and takes one position from the grid, then the program must switch the position to the next payer.

Step 7: Recording the Player’s Names to Observe on the Scoreboard

As we are maintaining the scoreboard to see what is the score against each player’s name after they have played multiple matches of the tic tac toe Python game, we will be using the main function in Python to capture and record the Player’s names to observe on the scoreboard at the end of the game.

Code :

Explanation :

Above shows the special variable__name__ that has the value of “main”. We use the input function in Python to provide the names of the two players. This will be captured as soon as the game starts when the entire program for the tic tac toe Python game gets executed.

Step 8: To Capture the Game Information

In the tic tac toe Python game, it’s always important to store the game information so that we are capturing the data related to the current player, the selection between the X or O that the players choose, the available options in the game which is either X or O and the scoreboard information.

Code :

Explanation :

As per the above code, we selected the current player as the first player along with storing the information on the selections made by both players as a dictionary, the available options in the game as a list, and the scoreboard information as a dictionary.

Step 9: To Design the Scoreboard

We shall be designing the Scoreboard as a dictionary data structure to keep a track of multiple games that the players play. here, the players’ names will act as the keys of the dictionary, and their respective wins shall be captured as the values.

Code :

Output :

Explanation :

We used the user-defined function my_scoreboard(score_board) which is taking score_board as the parameter where we define the variable that captures the names of the players in a list using the .keys() function in Python after which we index that as part of our score_board and show the respective scores which here is 0 as this is what shall be visible while the game starts.

As we are our game flexible enough to let the players play multiple games of tic tac toe Python, we shall require another loop for the same where we shall allow the current player to select the mark for each match. The selection menu will also be shown in each iteration of the game.

Code :

Output :

Explanation :

As seen above we implemented the while loop from Python to show the menu and give the current payer which is John here to make the choice for the series of the Tic tac toe Python game. John can now make use of action between the three options Cross ‘X’ or Naught ‘O’ or exit the game by pressing the respective key.

It’s very important to maintain the flow of the game to Handle Exceptions and Allot the selection of the symbol for the current player for each iteration of the game, for which we shall be using the try-exception block in Python as shown in the below code. The selection made by the current player will be captured and evaluated to let them know which player has won the game.

Code :

Explanation :

In the above snippet of code, we have used the try-exception block to handle any exception for the the_choice input. We have then used the if-else statement to create the choice menu for the current player to select from.

As per the selection made by the player, the data will be stored. This is significant as it will tell us which player won after every match.

Step 12: Execution of the Tic Tac Toe Python Game and Updating the Scoreboard Simultaneously

Now we are approaching the final part of our tic tac toe Python game, where we shall be executing an independent game between the two players and capture the win for the player. And as we have our scoreboard ready we shall also be updating it when the first game end as well.

Code :

Explanation :

As seen above, we captured the details of the winner of the tic tac toe Python game for a single match. we also used the if statement in Python to validate if the match is getting a tie or if one of the players is winning the game. If the game is a tie, then again the new match will start else when the game ends in a win the score of the player gets updated and the scoreboard gets updated too.

Step 13: Swapping the Chance Given to Choose the Symbol Between the Selecting Player

It is important to swap the chance given to choose the symbol between the players after each game has ended. While playing a game, it becomes mandatory to switch the chance of choosing the mark. For doing so, we shall be using the if-else statements in Python for letting the players switch the chance of selecting the mark (X or O) once one game has ended so that both the players get an equal chance to choose between the symbol.

Code :

Explanation :

Using the if-else statement in Python we created the possibility of giving each player an equal chance to choose between the Cross or Naught after each game has ended.

Step 14: It’s Gameplay Time

Now as we have understood each step in detail and the logic behind each let us compile all the above-created functions and execute our tic tac toe Python game to see it working and also to enjoy our very own created game!!

Code :

Output :

Please refer to the subsection – Final Output under the heading What we are building?

Elevate your coding skills with our Machine Coding Tic Tac Toe – LLD Case Study Course. Enroll now and master the art of low-level design!

Tic Tac Toe Python | How to code Tic Tac Toe in Python? | Great Learning
Tic Tac Toe Python | How to code Tic Tac Toe in Python? | Great Learning

Conclusion

Throughout this step-by-step project, you’ve created a classic tic-tac-toe computer game using Python and Tkinter. This GUI framework is available in the Python standard library. It runs on Windows, Linux, and macOS, so your game will work great on all three platforms. That’s pretty cool!

In this tutorial, you learned how to:

  • Implement the logic of the classic tic-tac-toe game using Python
  • Build the game’s board or GUI using Tkinter from the Python standard library
  • Connect the game’s logic and GUI to make the game work correctly

This knowledge provides you with the foundation for creating new and more complex games and GUI projects, which will help you take your Python skills to the next level.

Conclusion

  • Tic tac toe Python, also known as Noughts and Crosses or Xs and Os, is a very simple two-player game where both the player choose between the symbol ‘X’ and ‘O’ to mark the position on a 3X3 grid. Once a player is successful in marking a strike of the same symbol either in the horizontal, vertical, or diagonal way that player wins the game else the game goes on a draw if all the spots are filled.
  • We can access the above data from the Status of Grid which requires us to pass over the information every time we need to know the positions of each player. This is generally done by conserving time via the Time versus Space Complexity Trade-off.
  • The player_current variable that we used was to store the move of the current player as ‘X’ or ‘O’ in the tic tac toe in Python.
2 YEARS of PYTHON Game Development in 5 Minutes!
2 YEARS of PYTHON Game Development in 5 Minutes!

Overview

Have you ever tried implementing the most popular game – tic tac toe in Python programming language? We shall be creating an end-to-end tic tac-toe Python project and implementing the knowledge of Python that we have gained throughout the Python tutorial. Tic tac toe Python is a two-player game played on the 3X3 grid between two players. Each player chooses between X and O and the first player starts to draw the X on the space on the grid followed alternatively by the other until a player successfully marks a streak on the grid else if all spaces are filled the game is set to draw.

Keywords searched by users: xo game in python

Python Coding Tutorial: Build A Tic Tac Toe Game - Youtube
Python Coding Tutorial: Build A Tic Tac Toe Game – Youtube
Tic Tac Toe Game Using Pyqt5 In Python - Geeksforgeeks
Tic Tac Toe Game Using Pyqt5 In Python – Geeksforgeeks
Tic-Tac-Toe Game In Python 3 Using Tkinter (Tutorial) - Youtube
Tic-Tac-Toe Game In Python 3 Using Tkinter (Tutorial) – Youtube
Build A Tic-Tac-Toe Game With Python And Tkinter – Real Python
Build A Tic-Tac-Toe Game With Python And Tkinter – Real Python
Tic-Tac-Toe Game In Python
Tic-Tac-Toe Game In Python
Tic Tac Toe - Portfolio Project: Python Terminal Game - Codecademy Forums
Tic Tac Toe – Portfolio Project: Python Terminal Game – Codecademy Forums
Python Tic Tac Toe Tutorial | Beginner Friendly Tutorial - Youtube
Python Tic Tac Toe Tutorial | Beginner Friendly Tutorial – Youtube
My Tic-Tac-Toe Game - Portfolio Project: Python Terminal Game - Codecademy  Forums
My Tic-Tac-Toe Game – Portfolio Project: Python Terminal Game – Codecademy Forums
Tic Tac Toe Game With Gui Using Tkinter In Python - Geeksforgeeks
Tic Tac Toe Game With Gui Using Tkinter In Python – Geeksforgeeks
Build A Tic-Tac-Toe Game Engine With An Ai Player In Python – Real Python
Build A Tic-Tac-Toe Game Engine With An Ai Player In Python – Real Python
Tic Tac Toe In Python [ X/O ][ Pyhton 3 -- Pycharm ][ Windows ][ Tkinter ]  - Youtube
Tic Tac Toe In Python [ X/O ][ Pyhton 3 — Pycharm ][ Windows ][ Tkinter ] – Youtube

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *