Skip to content

Instantly share code, notes, and snippets.

@keyurshah
Created January 1, 2024 21:26
Show Gist options
  • Save keyurshah/f49d425854b4b9f47e586deeccd47072 to your computer and use it in GitHub Desktop.
Save keyurshah/f49d425854b4b9f47e586deeccd47072 to your computer and use it in GitHub Desktop.
# Function to print the current state of the board
def print_board(board):
# Iterate over the board in steps of 3 to print each row
for i in range(1, 10, 3):
# Print the current row of the board with corresponding values
print(f"{i}: {board[i]} {i+1}: {board[i+1]} {i+2}: {board[i+2]}\n")
# Function to check if there's a winner
def check_win(board):
# Define all possible winning combinations
winning_combinations = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 4, 7), (2, 5, 8), (3, 6, 9), (1, 5, 9), (3, 5, 7)]
# Iterate through each winning combination
for combo in winning_combinations:
# Check if the current combination is a winning one
if board[combo[0]] == board[combo[1]] == board[combo[2]] and board[combo[0]] != ' ':
# Return True if a winning combination is found
return True
# Return False if no winning combination is present
return False
# Main function to play Tic Tac Toe
def tic_tac_toe():
# Initialize the board with numbers 1 to 9 as keys and blank spaces as values
board = {i: ' ' for i in range(1, 10)}
# Print the initial empty board
print_board(board)
current_player = 'x' # Start with player 'x'
# Loop for each turn in the game (maximum of 9 turns)
for _ in range(9):
try:
# Prompt the current player to pick a number between 1 and 9
move = int(input(f"Player {current_player}, pick a number between 1 and 9: "))
# Check if the chosen number is outside the valid range
if move < 1 or move > 9:
# Inform the player about the invalid number and continue the loop
print("Invalid number. Please choose a number between 1 and 9.")
continue
# Check if the chosen spot is available
if board[move] == ' ':
# Assign the current player's symbol ('x' or 'o') to the chosen spot
board[move] = current_player
# Print the updated board
print_board(board)
# Check for a winning condition after the move
if check_win(board):
# Announce the winner and exit the game
print(f"Player {current_player} wins!")
return
# Switch to the other player for the next turn
current_player = 'o' if current_player == 'x' else 'x'
else:
# If the chosen spot is already taken, ask for a different number
print("That spot is already taken. Please choose another.")
except ValueError:
# Handle the case where the input is not a number
print("Please enter a valid number.")
# If the loop completes without a winner, declare a tie
print("It's a tie!")
# Start the game by calling the main function
tic_tac_toe()
@keyurshah
Copy link
Author

Of course! Let's break down those terms into simpler concepts:

Dictionary:

  • Dictionary: Think of a dictionary like a real-life dictionary. In a real dictionary, you look up a word (the key) to find its definition (the value). In Python, a dictionary is similar but can store all types of information, not just words and their meanings. Each entry in a Python dictionary has two parts: a key and a value. You use the key to find the corresponding value, much like you would in a real dictionary.

Strings:

  • String: A string is simply a series of characters. Anything inside quotes is considered a string in Python. This could be words, numbers, or symbols. For example, 'hello', "1234", and 'a!@' are all strings. They are used to store and manipulate text.

Other Terms:

  • Function: Imagine you have a little helper who does a specific task for you whenever you ask. In programming, this helper is called a function. You tell it what to do, and it does that task every time you ask. For example, in the game, one function prints the board, another checks if someone has won, and another controls the game's flow.

  • Loop: A loop is like a merry-go-round at a playground. You keep going around and around until you decide to stop. In programming, a loop repeats a set of instructions over and over again until a certain condition is met. For instance, in the game, the loop keeps going for each player's turn until the game is over.

  • Try-Except Block: Sometimes, things go wrong. Maybe you ask your friend for the 10th chocolate from a box that only has 5. They can't give you the 10th chocolate because it doesn't exist. In programming, this type of problem is called an exception. A try-except block helps handle these exceptions. You try to do something, and if it doesn't work (an exception occurs), the program doesn't just crash. Instead, the "except" part takes over and decides what to do next.

  • Boolean: In real life, many questions have a yes or no answer. Are you wearing shoes right now? Yes or No. In programming, we often need to check if something is true or false. Booleans are a way to do this. They can only be one of two values: True or False. They are often used to make decisions in code, like deciding if a game is over or not.

I hope these explanations help make these concepts clearer! Programming can be like learning a new language, but with practice, you'll start to understand and use these terms more naturally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment