Tic Tac Toe GUI In Python using PyGame
This article will guide you and give you a basic idea of designing a game Tic Tac Toe using pygame library of Python. Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Let’s break the task in five parts:
- Importing the required libraries and setting up the required global variables.
- Designing the game display function, that will set a platform for other components to be displayed on the screen.
- Main algorithm of win and draw
- Getting the user input and displaying the “X” or “O” at the proper position where the user has clicked his mouse.
- Running an infinite loop, and including the defined methods in it.
Note: The required PNG files can be downloaded below as follows:
Importing the required libraries and setting up the required global variables
We are going to use the pygame, time, and the sys library of Python. time library is used to keep track of time and sleep() method that we are going to use inside our code. Have a look at the code below.
Designing the game display
This is the trickier part, that makes the utmost importance in game development. We can use the display.set_mode() method to set up our display window. This takes three arguments, first one being a tuple having (width, height) of the display that we want it to be, the other two arguments are depth and fps respectively.display.set_caption(), sets a caption on the name tag of our display. pg.image.load() is an useful method to load the background images to customize the display. This method takes the file name as an argument along with the extension. There is a small problem with image.load(), it loads the image as a Python object in its native size, which may not be optimized along with the display. So we use another method in pygame known as pg.transform.scale(). This method takes two arguments, one being the name of the image object and the other is a tuple having (width, height), that we want our image to scale to. Finally we head to the first function, game_initiating_window(). On the very first line there is a screen.blit() function. The screen is the Python function and blit is the method that enables pygame to display something over another thing. Here out image object has been displayed over the screen, which was set white initially. pg.display.update() is another important function in game development. It updates the display of our window when called. Pygame also enables us to draw geometric objects like line, circle, etc. In this project we have used pg.draw.line() method that takes five arguments, namely – (display, line color, starting point, ending point, width). This involves a little bit of coordinate geometry to draw the lines properly. This is not sufficient. At each update of the display we need to know the game status, Whether it is win or lose.draw_status() helps us in displaying another 100pc window at the bottom of the main window, that updates the status at each click of the user.
The main algorithm has a straight forward approach. A user can win row-wise, column-wise, and diagonally. So by using a multidimensional array, we can set up the conditions easily.
Getting the user input and displaying the “X” or “O”
This part deals with a visualization of the board and a little bit of coordinate geometry. drawXO() takes two arguments row and col. First of all, we have to set up the correct geometrical position to put the image of X and image of O that we have stored as two python objects “x_img” and “y_img” respectively. Have a look at the code for a proper understanding. user_click() is a function we have designed to get the input from a user mouse click. Imagine, you have clicked on one of the nine parts (boxes divided by the lines we have drawn horizontally and vertically), this function will define the coordinate of the position where you have clicked.pg.mouse.get_pos() gets the x-coordinate and y-coordinate of the mouse click of the user and return a tuple. Depending upon the (x, y) we can define the exact row and the exact column where the user has clicked. Finally, when we have the row and col, we pass these two as arguments to the function drawXO(row, col) to draw the image of ‘X’ or the image of ‘O’ at the desired position of the user on the game screen.
Running an infinite loop
This is the final important step to run our game infinitely until the user clicks exit. Before running an infinite loop, we need to set up a function that can reset all the global values and parameters to initial values for a fresh start of the game. reset_game() is used for this purpose. It resets the board value to 3 * 3 None value again and initializes global parameters. In the game development, every action by the player is an event. Whether he clicks on the window or clicks on the exit/close icon. To get these events as an object, pygame has a built-in method used as pg.event.get(). If the event type is “QUIT”, we use the sys library of Python to exit the game. But if the mouse is pressed, the event.get() will return “MOUSEBUTTONDOWN” and our call to user_click() happens to know the exact coordinate of the board where the user has clicked. In the entire code, we have used the .sleep() method to pause our game for some time and make that user-friendly and smooth.
The complete code:
- The code starts by importing the required libraries.
- Then, it declares the global variables for storing the ‘x’ or ‘o’ value as character.
- Next, it stores the winner’s value at any instant of code.
- To check if the game is a draw, there is a variable called draw that will be set to None when we are done with this function and then used in other functions later on in this program.
- The next step is to set up some variables for width of the game window and height of the game window which will be 400 pixels wide and 400 pixels tall respectively.
- It also sets background color of the game window to white (255, 255, 255).
- The color of straightlines on that white board dividing into 9 parts is line_color = (0, 0, 0) while setting up a 3 * 3 board in canvas creates an empty array where each element has three spaces followed by two more elements which create nine squares on our tic tac toe board.
- Lastly it initializes pygame window with pg.init() method before loading images as python object using pg image library methods such as load(“modified_cover.png”) , x_img = pg .image .load(“X_modified.”), y_img = pg
- The code is a snippet of code that displays the game board in canvas.
- The code declares global variables such as winner, draw, XO and line_color.
- The code sets up the game window with width and height values.
- The background color is white which is set to be 255, 255, 255.
- The code starts by checking for the winner of the game.
- If there is no winner, then it prints “XO’s Turn” and sets a font object to print text on screen.
- The code checks for winning rows and columns.
- It also checks if there are diagonal winners in order to determine who won diagonally left or right.
- The next part of the code starts with a function called check_win().
- This function loops through all four possible combinations of winning rows and columns, which will be used later when determining who won diagonally left or right.
- After this loop finishes, it determines whether XO has won by checking if board == board == board.
- If so, then XO wins because they have three in a row horizontally (left-to-right) and two vertically (top-to-bottom).
- The code is a basic game of tic-tac-toe.
- The player who gets three in a row first wins the game.
- The code begins by declaring variables for the board, winner, and draw.
- The variable board will be used to store information about the current state of the game such as which rows and columns are won or lost.
- The variable winner will store information about who has won the game so far.
- The variable draw will hold whether or not there is a winner yet.
- After declaring these variables, two functions are created: check_win() and draw_status().
- These functions are called when it’s time to check if someone has won or when it’s time to update what is displayed on screen during gameplay
- The code starts by defining a function called drawXO.
- This function takes in two parameters: the row and the col of where to place an image on the screen.
- The first parameter is defined as being 30 from the left margin, so for each row, we need to define what position it should be pasted at.
- For example, if you wanted to paste an image over column 1, then you would set posx = width / 3 + 30.
- The next line defines that XO will always be ‘o’ when it’s not drawing anything else and ‘x’ when it is drawing something else.
- Then comes a function called user_click which gets coordinates of mouse clicks and draws images accordingly based on those coordinates.
- It also checks whether there is a winner or not before doing anything else with them (i.e., checking who won).
- Lastly, reset_game resets everything back to how they were originally before starting up again with game_initiating_window().
- The code is a program that plays Tic-Tac-Toe.
- The code starts by defining the board, which is an array of three rows and three columns with the value None in each cell.
- The game_initiating_window() function is called to start the game.
- If you want to play again, you can call reset_game().
- The while loop will continue until a user clicks on “Quit”.
Please Login to comment...