Home > Net >  Function for selected position in Tic Tac Toe
Function for selected position in Tic Tac Toe

Time:10-03

I'm trying to figure out how to implement a function that will store and print where the user wants to place an "X" in the game of Tic Tac Toe. If there are any other suggests you have to fix my code, it would be greatly appreciated. I just started coding so apologies if it looks terrible.

def print_board():
  game_board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]
  print(game_board[0]   " | "   game_board[1]   " | "   game_board[2])
  print(game_board[3]   " | "   game_board[4]   " | "   game_board[5])
  print(game_board[6]   " | "   game_board[7]   " | "   game_board[8])
print_board()

#selecting a space on the board
selection = int(input("Select a square: "))
try:
  if selection > 9 or  selection < 1:
    print("Sorry, please select a number between 1 and 9.")
  else:
    print(selection)
except ValueError:
    print("Oops! That's not a number. Try again...")

CodePudding user response:

You just need to keep asking until you get a valid number. Also, you need the "try" statement to wrap the function that will fail, in this case the int function. Here's a way to do it without try/except, which is really not the best choice here.

while True:
#selecting a space on the board
    selection = input("Select a square: ")
    if selection.isdigit():
        selection = int(selection)
        if 1 <= selection <= 9:
            break
        print("Sorry, please select a number between 1 and 9.")
    else:
        print("Oops! That's not a number. Try again...")

CodePudding user response:

Your code looks alright, there are a couple of things to look at though. First, you are storing the game_board inside of the print_board() function, so each time you run print_board() the gamestate resets. Also, your code does not update the board when the user types a number. This can be fixed by changing the corresponding value of the board to an "X", and for a list this is as simple as game_board[selection] = "X". So after those two changes your file might look like this:

game_board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]

def print_board():
  print(game_board[0]   " | "   game_board[1]   " | "   game_board[2])
  print(game_board[3]   " | "   game_board[4]   " | "   game_board[5])
  print(game_board[6]   " | "   game_board[7]   " | "   game_board[8])
print_board()

#selecting a space on the board
selection = int(input("Select a square: "))

try:
    if selection > 9 or  selection < 1:
        print("Sorry, please select a number between 1 and 9.")
    else:
        game_board[selection] = "X"
except ValueError:
    print("Oops! That's not a number. Try again...")

print_board()
  • Related