Noughts and Crosses/Tic Tac Toe

My first Python-based University coursework was to build a fully functioning GUI version of Noughts and Crosses in Python 3, with networking capability and the ability to play against an AI player.

My program utilised PyGame to achieve this, including a simple main menu and UI board to play on.

GUI

Loading the game will greet the player with a very simple but functional main menu. We were not awarded any marks for presentation, and thus I spent very little time making it.

Fig.1 – Main menu screen. The use of Comic Sans was intentional and will not be elaborated on

The game has support for singleplayer against an AI opponent, local multiplayer with 2 users on the same machine, and networked multiplayer, where two machines running the game can connect and play.

The game GUI consists of a large 512×512 sprite representing the board, as well as a plain white menu screen with the three gameplay options alongside an exit button. The game renders translucent versions of the player’s piece on the board when they hover the mouse over a square.

Fig.2 – Player 1 begins their first turn

The contents of each grid square is stored in an array, with simple maths used to check lines and adjacent grids for winning moves.

AI

The AI has a specific method for making moves. It checks if it can make a move that means it will win. If it cannot, it then checks if it can block the player from making a winning move. Finally, if it can do neither, it makes a random move. This behaviour quite accurately emulates a player who doesn’t have any particular strategy and poses a fair challenge to those who don’t know the best moves to start the game with.

This approach was achieved using simple if statements to check each option in the order described above. While consideration was given to program the AI to use the optimal technique for winning/forcing a draw, this was decided against as the player would never win. An AI is not a convincing opponent if it never makes mistakes.

Fig.3 – A game in progress

Networking

The networking side of the game works by attempting to connect to an existing game server. If this fails, the assumption is that a server does not exist, and the game then starts its own server. Once a player successfully joins a server, the game begins, and the host gets to make the first move. Each time a move is made, the game sends the number of the square on the grid that the move was made on, and the game updates the grid respectively on both the client and server. The game runs until one player wins or there is a draw.

Due to the security of the University computers, the networking function was only able to function on localhost, so no IP address input was added, as the task was simply to demonstrate the use of networking in the game.