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|improve this question









$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|improve this question









    $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|improve this question









      $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|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 53 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

          Сан-Квентин

          8-я гвардейская общевойсковая армия

          Алькесар