In today's discussion, we will create a simple but entertaining two-player game using Python - the classic Tic-Tac-Toe. We'll also examine the principles of game design logic along the way.
Before we begin, it's vital to note that the Python version we're using is 3.6. You should have a basic understanding of Python syntax and functions to follow along with the code.
Tic-Tac-Toe is a very straightforward game. The game board is a 3x3 grid, and the game is played by two players, who take turns. The first player marks moves with a cross 'X', and the second player uses a nought 'O'. The player who has formed a line of three marks wins.
Before the exciting coding part, let's understand the board construction. We can represent the game grid using a list in Python, where each element is a space ' ' which will eventually hold a player's move.
board = [' ' for x in range(10)]
Let's create a function to insert the player's plane - 'X' or 'O' on the board at a specific position.
def insert_board(letter, pos): board[pos] = letter
We need a function to check if any remaining spaces on the board are still empty.
def is_space_free(pos): return board[pos] == ' '
We need to visualize the current game state as we play, so let's write a function that prints out the board on the console.
def print_board(board): print(' | |') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('-----------') print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |')
Finally, we need a function that checks if a mark ('X' or 'O') has won.
def is_winner(bo, le): return (bo[7] == le and bo[8] == le and bo[9] == le) or (bo[4] == le and bo[5] == le and bo[6] == le) or(bo[1] == le and bo[2] == le and bo[3] == le) or (bo[1] == le and bo[4] == le and bo[7] == le) or (bo[2] == le and bo[5] == le and bo[8] == le) or (bo[3] == le and bo[6] == le and bo[9] == le) or (bo[1] == le and bo[5] == le and bo[9] == le) or (bo[3] == le and bo[5] == le and bo[7] == le)
That's it! You now have the foundation for the Tic-Tac-Toe game in Python. The next steps could involve creating a game flow control, implementing player turns, and refining the terminal interface. Happy coding!