The game is automatically launched by the program and therefore no user input is required. However, developing an automated game will be very fun. Let’s see how.
numpy
and random
Python libraries are used to create this game. Instead of asking the user to place a mark on the board, the code randomly selects a spot on the board and marks it. It will display the board after every move if the player doesn’t win. If the game gets a draw, it returns -1.
Explanation:
play_game ()
— this is the main function that does the following:
- Calls create_board () to create a 9x9 board and initializes at 0.
- For each player (1 or 2), calls the random_place () function to randomly select a place on the board and label that place with the player’s number.
- Print the board after each move.
- Evaluate the board after each move to check if there is a row, column or diagonal has the same player number. If so, the name of the winner is displayed. If after 9 moves there is no winner, -1 is displayed.
Below is the code for the above game:
|
Exit:
[[0 0 0] [0 0 0] [0 0 0]] Board after 1 move [[ 0 0 0] [0 0 0] [1 0 0]] Board after 2 move [[0 0 0] [0 2 0] [1 0 0]] Board after 3 move [[0 1 0] [0 2 0 ] [1 0 0]] Board after 4 move [[0 1 0] [2 2 0] [1 0 0]] Board after 5 move [[1 1 0] [2 2 0] [1 0 0]] Board after 6 move [[1 1 0] [2 2 0] [1 2 0]] Board after 7 move [[1 1 0] [2 2 0] [1 2 1]] Board after 8 move [[1 1 0 ] [2 2 2] [1 2 1]] Winner is: 2