Beginner Tic Tac Toe Game for Python

Is there anyway, I can have two passwords for my wi-fi

Sigmoid with a slope but no asymptotes?

What's the name of the logical fallacy where a debater extends a statement far beyond the original statement to make it true?

I'm just a whisper. Who am I?

Is there a distance limit for minecart tracks?

Determining multivariate least squares with constraint

Why is participating in the European Parliamentary elections used as a threat?

How do I tell my boss that I'm quitting in 15 days (a colleague left this week)

How to preserve electronics (computers, iPads and phones) for hundreds of years

Typing CO_2 easily

Is there a RAID 0 Equivalent for RAM?

How do I Interface a PS/2 Keyboard without Modern Techniques?

Animation: customize bounce interpolation

Mimic lecturing on blackboard, facing audience

How to get directions in deep space?

Sound waves in different octaves

Alignment of six matrices

What is the smallest number n> 5 so that 5 ^ n ends with "3125"?

Can I run 125kHz RF circuit on a breadboard?

What is the meaning of "You've never met a graph you didn't like?"

What happens if I try to grapple mirror image?

Can I say "fingers" when referring to toes?

How to make a list of partial sums using forEach

Did I make a mistake by ccing email to boss to others?



Beginner Tic Tac Toe Game for Python














0












$begingroup$


I am a beginner programmer and would like some feedback on this Tic Tac Toe game I made on Python. Any feedback would be appreciated, as I really want to get better at programming and pick up good habits. Here is my code. Something I would add is 'try' statements for invalid user input, but this is not important as I would like feedback on how to optimise this code. I would also love feedback on the check_if_win() function as I believe there might be a better way of doing this. Thank you!



"""Tic Tac Toe"""

__author__ = "Enrique Gonzalez Aretos"

EMPTY = " "
PLAYER_1 = "X"
PLAYER_2 = "O"

# Create Board
def create_board():
"""
Function which creates an empty game board
:return: <list<list<str>>> Returns the game board
"""
return [
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]
]
# Show board
def show_board(board):
"""
Function which prints the board for the user
:param board: <list<list<str>>> The Tic Tac Toe board
:return: <str> A clean-looking version of the board
"""
for x in board:
# Find better way to print this
print("|".join(x))

# Place X on spot
def place_player(board, active_player, row, column):
"""
Function which places the player into the board
:param board:
:param active_player:
:param row:
:param column:
:return:
"""
if board[row-1][column-1] == EMPTY:
board[row-1][column-1] = active_player

# Check if someone has won
def check_if_win(board, active_player):
"""
Function which checks if the active player has won
:param board: <list<list<str>>> Tic Tac Toe Board
:param active_player: <str> The current active player
:return: <bool> Return True or False
"""
# Making lists which will store the diagonals and columns of baord
diagonal1 = []
diagonal2 = []
column1 = []
column2 = []
column3 = []
# Diagonal counter is used to index the different values in each row
diagonal_counter = 1
for row in board:
# When each row is checked, the different indexes are organised
# into the column and diagonal lists
column1.append(row[0])
column2.append(row[1])
column3.append(row[2])
diagonal1.append(row[diagonal_counter-1])
diagonal2.append(row[-diagonal_counter])
diagonal_counter += 1
if "".join(row) == active_player * 3:
return True

# If statement which checks if any list is full of the active
# player's symbol
if "".join(column1) == active_player * 3 or "".join(column2) ==
active_player * 3 or "".join(column3) == active_player * 3:
return True
elif "".join(diagonal1) == active_player * 3 or "".join(diagonal2)
== active_player * 3:
return True
else:
return False

def swap_player(active_player):
if active_player == PLAYER_1:
return PLAYER_2
else:
return PLAYER_1


def main():
# Creates board and assigns starting player
board = create_board()
active_player = PLAYER_1
while True:
show_board(board)
# Ask for player input
row = int(input("nIt is 's turn play. Choose a row (1-3):
".format(active_player)))
column = int(input("Choose a column: "))
place_player(board, active_player, row, column)
# Checks if player has won
if check_if_win(board, active_player) is True:
show_board(board)
print("n won!".format(active_player))
break
active_player = swap_player(active_player)

if __name__ == "__main__":
main()








share









$endgroup$
















    0












    $begingroup$


    I am a beginner programmer and would like some feedback on this Tic Tac Toe game I made on Python. Any feedback would be appreciated, as I really want to get better at programming and pick up good habits. Here is my code. Something I would add is 'try' statements for invalid user input, but this is not important as I would like feedback on how to optimise this code. I would also love feedback on the check_if_win() function as I believe there might be a better way of doing this. Thank you!



    """Tic Tac Toe"""

    __author__ = "Enrique Gonzalez Aretos"

    EMPTY = " "
    PLAYER_1 = "X"
    PLAYER_2 = "O"

    # Create Board
    def create_board():
    """
    Function which creates an empty game board
    :return: <list<list<str>>> Returns the game board
    """
    return [
    [EMPTY, EMPTY, EMPTY],
    [EMPTY, EMPTY, EMPTY],
    [EMPTY, EMPTY, EMPTY]
    ]
    # Show board
    def show_board(board):
    """
    Function which prints the board for the user
    :param board: <list<list<str>>> The Tic Tac Toe board
    :return: <str> A clean-looking version of the board
    """
    for x in board:
    # Find better way to print this
    print("|".join(x))

    # Place X on spot
    def place_player(board, active_player, row, column):
    """
    Function which places the player into the board
    :param board:
    :param active_player:
    :param row:
    :param column:
    :return:
    """
    if board[row-1][column-1] == EMPTY:
    board[row-1][column-1] = active_player

    # Check if someone has won
    def check_if_win(board, active_player):
    """
    Function which checks if the active player has won
    :param board: <list<list<str>>> Tic Tac Toe Board
    :param active_player: <str> The current active player
    :return: <bool> Return True or False
    """
    # Making lists which will store the diagonals and columns of baord
    diagonal1 = []
    diagonal2 = []
    column1 = []
    column2 = []
    column3 = []
    # Diagonal counter is used to index the different values in each row
    diagonal_counter = 1
    for row in board:
    # When each row is checked, the different indexes are organised
    # into the column and diagonal lists
    column1.append(row[0])
    column2.append(row[1])
    column3.append(row[2])
    diagonal1.append(row[diagonal_counter-1])
    diagonal2.append(row[-diagonal_counter])
    diagonal_counter += 1
    if "".join(row) == active_player * 3:
    return True

    # If statement which checks if any list is full of the active
    # player's symbol
    if "".join(column1) == active_player * 3 or "".join(column2) ==
    active_player * 3 or "".join(column3) == active_player * 3:
    return True
    elif "".join(diagonal1) == active_player * 3 or "".join(diagonal2)
    == active_player * 3:
    return True
    else:
    return False

    def swap_player(active_player):
    if active_player == PLAYER_1:
    return PLAYER_2
    else:
    return PLAYER_1


    def main():
    # Creates board and assigns starting player
    board = create_board()
    active_player = PLAYER_1
    while True:
    show_board(board)
    # Ask for player input
    row = int(input("nIt is 's turn play. Choose a row (1-3):
    ".format(active_player)))
    column = int(input("Choose a column: "))
    place_player(board, active_player, row, column)
    # Checks if player has won
    if check_if_win(board, active_player) is True:
    show_board(board)
    print("n won!".format(active_player))
    break
    active_player = swap_player(active_player)

    if __name__ == "__main__":
    main()








    share









    $endgroup$














      0












      0








      0





      $begingroup$


      I am a beginner programmer and would like some feedback on this Tic Tac Toe game I made on Python. Any feedback would be appreciated, as I really want to get better at programming and pick up good habits. Here is my code. Something I would add is 'try' statements for invalid user input, but this is not important as I would like feedback on how to optimise this code. I would also love feedback on the check_if_win() function as I believe there might be a better way of doing this. Thank you!



      """Tic Tac Toe"""

      __author__ = "Enrique Gonzalez Aretos"

      EMPTY = " "
      PLAYER_1 = "X"
      PLAYER_2 = "O"

      # Create Board
      def create_board():
      """
      Function which creates an empty game board
      :return: <list<list<str>>> Returns the game board
      """
      return [
      [EMPTY, EMPTY, EMPTY],
      [EMPTY, EMPTY, EMPTY],
      [EMPTY, EMPTY, EMPTY]
      ]
      # Show board
      def show_board(board):
      """
      Function which prints the board for the user
      :param board: <list<list<str>>> The Tic Tac Toe board
      :return: <str> A clean-looking version of the board
      """
      for x in board:
      # Find better way to print this
      print("|".join(x))

      # Place X on spot
      def place_player(board, active_player, row, column):
      """
      Function which places the player into the board
      :param board:
      :param active_player:
      :param row:
      :param column:
      :return:
      """
      if board[row-1][column-1] == EMPTY:
      board[row-1][column-1] = active_player

      # Check if someone has won
      def check_if_win(board, active_player):
      """
      Function which checks if the active player has won
      :param board: <list<list<str>>> Tic Tac Toe Board
      :param active_player: <str> The current active player
      :return: <bool> Return True or False
      """
      # Making lists which will store the diagonals and columns of baord
      diagonal1 = []
      diagonal2 = []
      column1 = []
      column2 = []
      column3 = []
      # Diagonal counter is used to index the different values in each row
      diagonal_counter = 1
      for row in board:
      # When each row is checked, the different indexes are organised
      # into the column and diagonal lists
      column1.append(row[0])
      column2.append(row[1])
      column3.append(row[2])
      diagonal1.append(row[diagonal_counter-1])
      diagonal2.append(row[-diagonal_counter])
      diagonal_counter += 1
      if "".join(row) == active_player * 3:
      return True

      # If statement which checks if any list is full of the active
      # player's symbol
      if "".join(column1) == active_player * 3 or "".join(column2) ==
      active_player * 3 or "".join(column3) == active_player * 3:
      return True
      elif "".join(diagonal1) == active_player * 3 or "".join(diagonal2)
      == active_player * 3:
      return True
      else:
      return False

      def swap_player(active_player):
      if active_player == PLAYER_1:
      return PLAYER_2
      else:
      return PLAYER_1


      def main():
      # Creates board and assigns starting player
      board = create_board()
      active_player = PLAYER_1
      while True:
      show_board(board)
      # Ask for player input
      row = int(input("nIt is 's turn play. Choose a row (1-3):
      ".format(active_player)))
      column = int(input("Choose a column: "))
      place_player(board, active_player, row, column)
      # Checks if player has won
      if check_if_win(board, active_player) is True:
      show_board(board)
      print("n won!".format(active_player))
      break
      active_player = swap_player(active_player)

      if __name__ == "__main__":
      main()








      share









      $endgroup$




      I am a beginner programmer and would like some feedback on this Tic Tac Toe game I made on Python. Any feedback would be appreciated, as I really want to get better at programming and pick up good habits. Here is my code. Something I would add is 'try' statements for invalid user input, but this is not important as I would like feedback on how to optimise this code. I would also love feedback on the check_if_win() function as I believe there might be a better way of doing this. Thank you!



      """Tic Tac Toe"""

      __author__ = "Enrique Gonzalez Aretos"

      EMPTY = " "
      PLAYER_1 = "X"
      PLAYER_2 = "O"

      # Create Board
      def create_board():
      """
      Function which creates an empty game board
      :return: <list<list<str>>> Returns the game board
      """
      return [
      [EMPTY, EMPTY, EMPTY],
      [EMPTY, EMPTY, EMPTY],
      [EMPTY, EMPTY, EMPTY]
      ]
      # Show board
      def show_board(board):
      """
      Function which prints the board for the user
      :param board: <list<list<str>>> The Tic Tac Toe board
      :return: <str> A clean-looking version of the board
      """
      for x in board:
      # Find better way to print this
      print("|".join(x))

      # Place X on spot
      def place_player(board, active_player, row, column):
      """
      Function which places the player into the board
      :param board:
      :param active_player:
      :param row:
      :param column:
      :return:
      """
      if board[row-1][column-1] == EMPTY:
      board[row-1][column-1] = active_player

      # Check if someone has won
      def check_if_win(board, active_player):
      """
      Function which checks if the active player has won
      :param board: <list<list<str>>> Tic Tac Toe Board
      :param active_player: <str> The current active player
      :return: <bool> Return True or False
      """
      # Making lists which will store the diagonals and columns of baord
      diagonal1 = []
      diagonal2 = []
      column1 = []
      column2 = []
      column3 = []
      # Diagonal counter is used to index the different values in each row
      diagonal_counter = 1
      for row in board:
      # When each row is checked, the different indexes are organised
      # into the column and diagonal lists
      column1.append(row[0])
      column2.append(row[1])
      column3.append(row[2])
      diagonal1.append(row[diagonal_counter-1])
      diagonal2.append(row[-diagonal_counter])
      diagonal_counter += 1
      if "".join(row) == active_player * 3:
      return True

      # If statement which checks if any list is full of the active
      # player's symbol
      if "".join(column1) == active_player * 3 or "".join(column2) ==
      active_player * 3 or "".join(column3) == active_player * 3:
      return True
      elif "".join(diagonal1) == active_player * 3 or "".join(diagonal2)
      == active_player * 3:
      return True
      else:
      return False

      def swap_player(active_player):
      if active_player == PLAYER_1:
      return PLAYER_2
      else:
      return PLAYER_1


      def main():
      # Creates board and assigns starting player
      board = create_board()
      active_player = PLAYER_1
      while True:
      show_board(board)
      # Ask for player input
      row = int(input("nIt is 's turn play. Choose a row (1-3):
      ".format(active_player)))
      column = int(input("Choose a column: "))
      place_player(board, active_player, row, column)
      # Checks if player has won
      if check_if_win(board, active_player) is True:
      show_board(board)
      print("n won!".format(active_player))
      break
      active_player = swap_player(active_player)

      if __name__ == "__main__":
      main()






      python beginner





      share












      share










      share



      share










      asked 5 mins ago









      EnriqueEnrique

      385




      385




















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215893%2fbeginner-tic-tac-toe-game-for-python%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215893%2fbeginner-tic-tac-toe-game-for-python%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Why is a white electrical wire connected to 2 black wires?How to wire a light fixture with 3 white wires in box?How should I wire a ceiling fan when there's only three wires in the box?Two white, two black, two ground, and red wire in ceiling box connected to switchWhy is there a white wire connected to multiple black wires in my light box?How to wire a light with two white wires and one black wireReplace light switch connected to a power outlet with dimmer - two black wires to one black and redHow to wire a light with multiple black/white/green wires from the ceiling?Ceiling box has 2 black and white wires but fan/ light only has 1 of eachWhy neutral wire connected to load wire?Switch with 2 black, 2 white, 2 ground and 1 red wire connected to ceiling light and a receptacle?

          कुँवर स्रोत दिक्चालन सूची"कुँवर""राणा कुँवरके वंशावली"

          सि.चक भराडी, कोश्याँकुटोली तहसील इन्हें भी देखें बाहरी कड़ियाँ दिक्चालन सूची(निर्देशांक ढूँढें)www.uttara.gov.inउत्तराखण्ड - भारत सरकार के आधिकारिक पोर्टल परउत्तराखण्ड सरकार का आधिकारिक जालपृष्ठउत्तराखण्डउत्तरा कृषि प्रभासंबढ़ाने मेंसं