0

I am learning to use Python from Udemy Zero to Hero course and am really struggling with the milestone#1 project. I am creating a very simple tic tac toe game and I have gotten only has far as creating 1) a board 2) assigning each player 3) putting first player on the board. I will be honest i am not sure if the code I did is a good way to do any of this, but I am a bit confused 1.) if I should be using parameters(still a bit confused by when and when not to use them- maybe it will help the code be more flexible?) as my code works without it, and 2) what I should do next- I know I need to create a function to see if its been won, tied or lost but not sure how to bring that function back to the ones I have made-should make the return of that function be a boolean and then try to use it elsewhere? Any help would be appreciated to help me progress forward as I don't want to look at the solutions until I can at least somewhat create something myself.

FYI i am using pycharm if that matters

Thanks!

board = [' '] * 9
player_1 = None
player_2 = None
current_player = None
position = None
acceptable_range = [0,1,2,3,4,5,6,7,8]
players = None

def game_board(board):
    print('\n' * 100)
    print(board[0] + "|" + board[1] + "|" + board[2])
    print(" --- ")
    print(board[3] + "|" + board[4] + "|" + board[5])
    print(" --- ")
    print(board[6] + "|" + board[7] + "|" + board[8])


def assign_players():
    #only allow 'X' or 'O'
    acceptable_values= ['X','O']
    # asks player 1 what letter he wants
    global player_1
    global player_2
    global current_player
    global players
    player_1 = input('Player 1 would you like to be X or O: ').upper()
    while player_1 not in acceptable_values:
        player_1 = input('Please choose only X or O: ').upper()

    if player_1 == 'X':
        player_2 = 'O'
    else:
        player_2 = 'X'
    players = [player_1, player_2]



def position_placement():
    #request input from player_1 and make sure its int and within range
    global acceptable_range
    global current_player
    global position
    global players

    current_player = players[0]

    while position == None:
        position = int(input('Please choose a number between 0-8: '))
        while position not in acceptable_range:
            position = int(input('Incorrect value! Sorry please try again: '))

    # take position and assign to player_1 value
    board[position] = current_player
    # pop off position from acceptable_range so it can't be chosen again
    acceptable_range.pop(position)

    #show the new board
    return (game_board(board))
  • 2
    don't use global variables. unless specifically instructed in the course, you should avoid using global variables. – Sembei Norimaki Jun 28 '23 at 11:48
  • 1
    Hello. Question about if you "should" do this or that does not match the criteria of this site. https://codereview.stackexchange.com/ seems a better fit. Moreover, for SO, please ask only one question per question. – Itération 122442 Jun 28 '23 at 11:50
  • Some justifications on why you should not be using global variables can be found [here](https://stackoverflow.com/a/59330720/19593035). – rochard4u Jun 28 '23 at 11:51
  • @Itération122442 "what I should do next- I know I need to create a function to see if its been won, tied or lost but not sure how to bring that function back to the ones I have made-should make the return of that function be a boolean and then try to use it elsewhere?" Is not at all on-topic on Code Review. – Peilonrayz Jun 28 '23 at 11:56

1 Answers1

0
import sys #importing a sys module

#sorry for my bad english, i'm brazilian and don't speek english too well, hope you understand! :)

board = [' '] * 9
def game_board(): #function that show the gameboard
  board_representation = ''
  for i in range(len(board)): #read and show the board with numbers on it
    if board[i] == ' ':
      board_representation += str(i)
    else:
      board_representation += board[i]
    if (i + 1) % 3 == 0 and i != 8:
      board_representation += '\n---------\n'
    elif i != 8:
      board_representation += ' | '
  return board_representation


def check_winner():
  for i in range(0, 9, 3): #checks the horizontal rools to see if it has a winner 
    if board[i] == board[i + 1] == board[i + 2] != ' ':
      return board[i] #return a value to verify if we have a winner

  for i in range(3): #checks the vertical rools to see if it has a winner on it
    if board[i] == board[i + 3] == board[i + 6] != ' ':
      return board[i] #return a value to verify if we have a winner

  if board[0] == board[4] == board[8] != ' ': #checks the diagonal starting by the top right
    return board[0]
  if board[2] == board[4] == board[6] != ' ': #checks the diagonal starting by the top left
    return board[2] #return a value to verify if we have a winner

  return None #if none of the checks return a value, return None


def players(): #function that define if player_1 is X or O
  print()
  print('Player_1: ')
  player_1 = input('X or O? ').upper()
  if player_1 == 'X': #if player_1 = X than player_2 has to be O
    player_2 = 'O'
  elif player_1 == 'O': #if player_1 = O than player_2 has to be X
    player_2 = 'X'
  else:
    player_1 == 'X' #if the player_1 mistipe anything the code assumes that him is X to avoid problems
    player_2 == 'O'

  return player_1, player_2 #return X, O


def turn_players(player_1, player_2):
  turn = player_1 #turn will start with player_1 goins first

  while ' ' in board: ## check's if has any empty spaces on the board, if it has, the game has no winners and stop
    if turn == player_1:
      while True: #infinity loop
        print('Player_1:')
        play = input('Type a digit between 0 and 8 to play: ') #ask the number that player one will use to make the move

        try:
          play = int(play) #try to convert the str that comes from the imput play to a int

          if play < 9: #checks if the player typed a number lower than 9 to use that space on the board

            if board[play] == ' ': #checks if the player selected a empty slot to play
              board[play] = player_1 #remenber that player_1 and player_2 are strings 'X' or 'O', this line feel a empty space with X or O 
              turn = player_2 #pass the turn to player_2, because to start the loop it checks if its player one or two turn
              print(game_board()) #show the updated board
              winner = check_winner() #checks after the play if we had a winner
              if winner: #if we had a winner it prints it
                print('Player_1 Won!')
                sys.exit() #this function is imported from sys, it makes the program fully stop
              break

            else: #if the player trys to play on a empty spaces it show this message and restard his turn
              print(
                'That position is already taken. Choose an empty position.')
              continue

          else: #if the player try to play in a slot > 8 show this messa ge and restart his turn
            print('Only numbers up to 8 are acceptable.')
            continue

        except ValueError: #if the player type anything thats not a number, tells him to only types a number and reestart tha loop
          print('Only numbers are acceptable.')
          continue

    elif turn == player_2: #the exact same as the player_1 code
      while True:
        print('Player_2:')
        play = input('Type a digit between 0 and 8 to play: ')

        try:
          play = int(play)
          if play < 9:
            if board[play] == ' ':
              board[play] = player_2
              turn = player_1
              print(game_board())
              winner = check_winner()
              if winner:
                print('Player_2 Venceu!')
                sys.exit()
              break
            else:
              print(
                'That position is already taken. Choose an empty position.')
              continue
          else:
            print('Only numbers up to 8 are acceptable.')
            continue

        except ValueError:
          print('Only numbers are acceptable.')
          continue


print(game_board()) #prints the board
player_1, player_2 = players() #the players() function returns two values, so i declare two variables to it
turn_players(player_1, player_2) #execute the main function of the code
  • First of all, thanks for your effort in helping answer this question. However, please don't add new answers, simply edit your original answer or if that is a problem, delete one of the answers unless the second answer is vastly different from the first. – itprorh66 Jun 28 '23 at 20:04
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 30 '23 at 07:16