A great way of learning a language is developing fun projects in it. Learning various informative functions of a project in a fun way leads to developing creative games that are helpful in learning and are fun to play. Game development is one of the most rewarding and teaching tools in any language. Developing any game requires to work efficiently using logics, mathematics, artificial intelligence, and clears numerous concepts regarding a specified programming language.
Tic Tac Toe with Python
Tic tac toe is a well-known grid game known as ‘X’s and ‘O’s. It is originally a paper and pencil game for two players taking turns. Even though it can have game boards of multiple sizes, however, in the classic tic tac toe, there is generally a grid board of 3*3 squares. In this two-player game, each player takes turns to mark the squares. The player who successfully places assigned three marks in a horizontal, vertical, or diagonal row wins the game.
A sample picture of the Tic Tac Toe game is following for visualization:
Requirements and Conditions of the Game
In this Tic Tac Toe, the user wants to develop the game for two users (not computer) who take turns to play, and the game algorithm decided the end-result of the game. Before starting the code, the users must decide on the requirements and game outcome conditions. Following are the game requirement and result conditions for this tic TAC toe tutorial:
- The game board should be three squares by three squares.
- The users should choose their markers, for instance, X and O.
- The game should allow the first player to mark ‘X’ in any one of the squares.
- The game should allow the second player to mark ‘O’ in any of the unmarked squares.
- Players should each take turns marking ‘X’s and ‘O’s until there are no unmarked squares left.
- In the case where at the end, no row, column, or diagonal has the same marker, the game is a draw.
- If any row, column, or diagonal has the same markers, in the end, the player who marked them wins the game.
- The players should be able to start the game again once it is over.
Python Example
Below is the python tutorial to build a basic Tic Tac Toe game for two players:
- While implementing the game algorithm, the user needs to first decide on the input of the game. This decision means that both players should enter their input without clicking on the squares because the game does not have a GUI (Graphic User Interface) in the beginner’s tutorial. Therefore, the user can build the game board in the following way by making an array of nine entries.
Board = {'7' , '8' , '9', '4' , '5' , '6', '1' , '2' , '3'}
- Moreover, as the game needs to update and show the new board to the players after each turn, the user should make a printer function as shown in the code to print the updated game board.
def printer(gameboard): print(gameboard['7'] + '|' + gameboard['8'] + '|' + gameboard['9']) print('-+-+-') print(gameboard['4'] + '|' + gameboard['5'] + '|' + gameboard['6']) print('-+-+-') print(gameboard['1'] + '|' + gameboard['2'] + '|' + gameboard['3'])
- The user defines the gamestart() function, which is a primary function for the game. In this function, the user first asks the players to enter their markers, such as ‘X’ and ‘O’.
def gamestart(): printer("Player 1: Enter your marker") mark1 = input() printer("Player 2: Enter your marker") mark2 = input()
- Furthermore, the game boards in Tic Tac Toe should have 9 squares; therefore, in any case, the players can have utmost 9 turns. So, the user places the game algorithm in a while loop that runs 9 times. The game takes the input from the players who specify the square’s position in each iteration, ranged between 1 and 9, to mark that square. The algorithm checks if that position is empty to be marked or not and then decides based on it. If the opponent has not marked that square, the algorithm marks it. Otherwise, it shows the message that “the position is not vacant, and the player should choose some other square.”
marker = mark1 for temp in range(10): printer(Board) print(marker + ": Enter the box you want to select"); m1 = input() if Board[m1] != mark1 and Board[m1] != mark2: Board[m1] = m1 else: print("That place is already filled.\n Choose some other place") continue if marker == mark1: marker = mark2 else: marker = mark1
- Moreover, the algorithm keeps the check of turn numbers using the counter variable. It is intuitional that the counter should be at least 5 for any user to have a chance at winning. That is why, after 5 inputs, the algorithm checks that if any row, column, or diagonal has the same markers. If that is the case, then the owner of those markers, i.e., the player who marked those positions, wins the game, and the algorithm prints the “game over” message and announces the player’s win.
counter =0 for temp in range(10): printer(Board) print(marker + ": Enter the box you want to select"); m1 = input() if Board[m1] != mark1 and Board[m1] != mark2: Board[m1] = m1 counter += 1 else: print("That place is already filled.\n Choose some other place") continue #checking if some one won the game if counter >= 5: if Board['7'] == Board['8'] == Board['9'] : printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['4'] == Board['5'] == Board['6'] : printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['1'] == Board['2'] == Board['3'] : printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['1'] == Board['4'] == Board['7'] : printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['2'] == Board['5'] == Board['8'] : printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['3'] == Board['6'] == Board['9'] : printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['7'] == Board['5'] == Board['3'] : printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['1'] == Board['5'] == Board['9'] ': printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break
- Even though the game’s outcome becomes visible in the while loop; however, there can be cases when no user wins, i.e., the game is a draw. It means that no row, column, or diagonal had the same markers even after the 9 turns. In that case, the algorithm prints the “game over” with the “game draw” message.
if counter == 9: print("\nGame Over.\n") print("Game tie")
- Finally, when the game is over, the algorithm shows the restart message to ask the players either they want to play the game again or not? If the players want to play again, it clears the board and calls the gamestart() function again to start the game.
reset = input("Do want to play it again?(y/n)") if reset == "Y" or reset == "y": for i in Board: Board[i] = 'i' gamestart()
- In this way, the users can code their versions of Tic Tac Toe by building on it. Below is the compilation of all the above code chunks:
Board = {'7' , '8' , '9', '4' , '5' , '6', '1' , '2' , '3'} def printer(gameboard): print(gameboard['7'] + '|' + gameboard['8'] + '|' + gameboard['9']) print('-+-+-') print(gameboard['4'] + '|' + gameboard['5'] + '|' + gameboard['6']) print('-+-+-') print(gameboard['1'] + '|' + gameboard['2'] + '|' + gameboard['3']) def gamestart(): printer("Player 1: Enter your marker") mark1 = input() printer("Player 2: Enter your marker") mark2 = input() marker = mark1 counter =0 for temp in range(10): printer(Board) print(marker + ": Enter the box you want to select"); m1 = input() if Board[m1] != mark1 and Board[m1] != mark2: Board[m1] = m1 counter += 1 else: print("That place is already filled.\n Choose some other place") continue #checking if some one won the game if counter >= 5: if Board['7'] == Board['8'] == Board['9'] != ' ': printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['4'] == Board['5'] == Board['6'] != ' ': printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['1'] == Board['2'] == Board['3'] != ' ': printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['1'] == Board['4'] == Board['7'] != ' ': printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['2'] == Board['5'] == Board['8'] != ' ': printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['3'] == Board['6'] == Board['9'] != ' ': printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['7'] == Board['5'] == Board['3'] != ' ': printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break elif Board['1'] == Board['5'] == Board['9'] != ' ': printer(Board) print("\nGame Over.\n") print(" **** " +m1 + " won. ****") break if counter == 9: print("\nGame Over.\n") print("Game tie") if marker == mark1: marker = mark2 else: marker = mark1 reset = input("Do want to play it again?(y/n)") if reset == "Y" or reset == "y": for i in Board: Board[i] = 'i' gamestart()
There is another algorithm that users can use to enhance their TicTacToe game. In that case, they can include the option of playing with the computer.
Minimax Algorithm
In the language of programming, the TicTacToe game is a zero-sum and perfect solution game. Therefore, the minimax algorithm is the best choice for solving such problems. Although this algorithm is extremely efficient, the developers use it when they are giving the option to play with the computer.
This algorithm works for zero-sum games between two players: tic tac toe, chess, go, and checkers. Recursive search is utilized in this algorithm to find the best move at the current state.
- It analyzes the current state and available next moves at this point.
- It selects the best move for the current player to win or at least draw the game.
- It works in alternating min and max until the final state, win, lose, or draw.
Platform to Enhance the game
As the visualization of any project helps in faster learning of programming concepts and developing games is a creative way of doing it. Moreover, the games with better interfaces are captivating and easy for players to enjoy the game and return for it again. Therefore, users can use platforms such as PyGame to develop this game.
What is PyGame?
Having the basic knowledge of programming in Python, such as the clear concepts about user-defined functions, importing libraries and modules, using loops and conditions, and basic knowledge about working with files on the platform proves helpful in developing creative games using PyGame. PyGame consists of a unique set of modules in Python, designed for the sole purpose of developing video games. PyGame adds functionalities to the SDL library, which helps create fully featured games and multimedia programs in Python.
The most rewarding thing about using PyGame is that it is portable, and the developers can use it on cross platforms without causing any problems. It also operates with almost every operating system widening its range of platforms. Moreover, it is free of cost and released under the LGPL license, so creating open-source, freeware, and shareware games is a special add-on.