Beginner's user vs. computer Tic Tac Toe











up vote
1
down vote

favorite












I made a simply user vs. computer game on Tic Tac Toe. I used Object Oriented Programming to increase my understanding of this programming paradigm. Can you criticize any design flaws I have in my code?



#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 15 20:56:48 2018

@author: von-vic
"""
import random
from itertools import combinations

class Board(object):

def __init__(self):
self.board = {x:None for x in (7,8,9,4,5,6,1,2,3)}

def display(self):
"""
Displays tic tac toe board
"""
d_board = 'nTIC TAC TOE:n'
for pos, obj in self.board.items():
if obj == None:
d_board += '_'
elif obj == 'X':
d_board += 'X'
elif obj == 'O':
d_board += 'O'

if pos%3 == 0:
d_board += 'n'
print(d_board)

def getAvailable(self):
"""
Returns available positions
"""
available =
for pos, obj in self.board.items():
if obj == None:
available.append(pos)
return available

class Tic_Tac_Toe(Board):
pieces = ['O', 'X']

def __init__(self):
super().__init__()
self.piece = Tic_Tac_Toe.pieces.pop(random.choice([0,1]))
self.cp_piece = Tic_Tac_Toe.pieces[0]

def user_setName(self, name):
self.name = name

def user_setPiece(self, position):
"""
Position parameter denoted by a number on the keypad (1-9)
"""
self.board[position] = self.piece

def user_getPiece(self):
return self.piece

def cp_setPiece(self):
self.board[random.choice(self.getAvailable())] = self.cp_piece

def cp_getPiece(self):
return self.cp_piece

def checkWin(self, player):
"""
Checks if move by either the user or computer results in a win
"""
def at_least_one(A, B):
for i in A:
for j in B:
if i == j:
return True
return False

win_patterns = [(1,2,3),(4,5,6),(7,8,9),
(1,4,7),(2,5,8),(3,6,9),
(3,5,7),(1,5,9)]
spots = [k for k, v in self.board.items() if v == player]
spots.sort()
player_combinations = list(combinations(spots,3))
if at_least_one(player_combinations, win_patterns) == True:
return True
return False

def checkFullBoard(self):
if None not in self.board.values():
self.display()
print('Draw! Game board full!')
return True
return False

#---------

def main():
# Setup game
game = Tic_Tac_Toe()
input('Hello user! Welcome to Tic Tac Toe! Press any key to continue')

if game.user_getPiece() == 'X':
print('You are X. You are going first.')
else:
print('You are O. You are going second.')
game.cp_setPiece()

# Main game loop
while True:
game.display()
position = input('Use the number pad on the lefthand side of your keyboardnto select your position (1-9):')

try:
position = int(position)
if position in range(1,10):
if position in game.getAvailable():
game.user_setPiece(position)
else:
print('----Please input an available position.')
continue
else:
print('----Please input a number between 1 and 9.')

except ValueError:
print('----Please input a number.')
continue

# FOR USER
# Check for win
if game.checkWin(game.user_getPiece()) == True:
game.display()
print('Congratulations! You win!')
break

# Check for full board
if game.checkFullBoard() == True:
break

# FOR COMPUTER
game.cp_setPiece()
# Check for win
if game.checkWin(game.cp_getPiece()) == True:
game.display()
print('Sorry. You lost.')
break

# Check for full board
if game.checkFullBoard() == True:
break

if __name__ == '__main__':
main()









share|improve this question









New contributor




Von Vic Cayas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    up vote
    1
    down vote

    favorite












    I made a simply user vs. computer game on Tic Tac Toe. I used Object Oriented Programming to increase my understanding of this programming paradigm. Can you criticize any design flaws I have in my code?



    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    """
    Created on Sat Dec 15 20:56:48 2018

    @author: von-vic
    """
    import random
    from itertools import combinations

    class Board(object):

    def __init__(self):
    self.board = {x:None for x in (7,8,9,4,5,6,1,2,3)}

    def display(self):
    """
    Displays tic tac toe board
    """
    d_board = 'nTIC TAC TOE:n'
    for pos, obj in self.board.items():
    if obj == None:
    d_board += '_'
    elif obj == 'X':
    d_board += 'X'
    elif obj == 'O':
    d_board += 'O'

    if pos%3 == 0:
    d_board += 'n'
    print(d_board)

    def getAvailable(self):
    """
    Returns available positions
    """
    available =
    for pos, obj in self.board.items():
    if obj == None:
    available.append(pos)
    return available

    class Tic_Tac_Toe(Board):
    pieces = ['O', 'X']

    def __init__(self):
    super().__init__()
    self.piece = Tic_Tac_Toe.pieces.pop(random.choice([0,1]))
    self.cp_piece = Tic_Tac_Toe.pieces[0]

    def user_setName(self, name):
    self.name = name

    def user_setPiece(self, position):
    """
    Position parameter denoted by a number on the keypad (1-9)
    """
    self.board[position] = self.piece

    def user_getPiece(self):
    return self.piece

    def cp_setPiece(self):
    self.board[random.choice(self.getAvailable())] = self.cp_piece

    def cp_getPiece(self):
    return self.cp_piece

    def checkWin(self, player):
    """
    Checks if move by either the user or computer results in a win
    """
    def at_least_one(A, B):
    for i in A:
    for j in B:
    if i == j:
    return True
    return False

    win_patterns = [(1,2,3),(4,5,6),(7,8,9),
    (1,4,7),(2,5,8),(3,6,9),
    (3,5,7),(1,5,9)]
    spots = [k for k, v in self.board.items() if v == player]
    spots.sort()
    player_combinations = list(combinations(spots,3))
    if at_least_one(player_combinations, win_patterns) == True:
    return True
    return False

    def checkFullBoard(self):
    if None not in self.board.values():
    self.display()
    print('Draw! Game board full!')
    return True
    return False

    #---------

    def main():
    # Setup game
    game = Tic_Tac_Toe()
    input('Hello user! Welcome to Tic Tac Toe! Press any key to continue')

    if game.user_getPiece() == 'X':
    print('You are X. You are going first.')
    else:
    print('You are O. You are going second.')
    game.cp_setPiece()

    # Main game loop
    while True:
    game.display()
    position = input('Use the number pad on the lefthand side of your keyboardnto select your position (1-9):')

    try:
    position = int(position)
    if position in range(1,10):
    if position in game.getAvailable():
    game.user_setPiece(position)
    else:
    print('----Please input an available position.')
    continue
    else:
    print('----Please input a number between 1 and 9.')

    except ValueError:
    print('----Please input a number.')
    continue

    # FOR USER
    # Check for win
    if game.checkWin(game.user_getPiece()) == True:
    game.display()
    print('Congratulations! You win!')
    break

    # Check for full board
    if game.checkFullBoard() == True:
    break

    # FOR COMPUTER
    game.cp_setPiece()
    # Check for win
    if game.checkWin(game.cp_getPiece()) == True:
    game.display()
    print('Sorry. You lost.')
    break

    # Check for full board
    if game.checkFullBoard() == True:
    break

    if __name__ == '__main__':
    main()









    share|improve this question









    New contributor




    Von Vic Cayas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I made a simply user vs. computer game on Tic Tac Toe. I used Object Oriented Programming to increase my understanding of this programming paradigm. Can you criticize any design flaws I have in my code?



      #!/usr/bin/env python3
      # -*- coding: utf-8 -*-
      """
      Created on Sat Dec 15 20:56:48 2018

      @author: von-vic
      """
      import random
      from itertools import combinations

      class Board(object):

      def __init__(self):
      self.board = {x:None for x in (7,8,9,4,5,6,1,2,3)}

      def display(self):
      """
      Displays tic tac toe board
      """
      d_board = 'nTIC TAC TOE:n'
      for pos, obj in self.board.items():
      if obj == None:
      d_board += '_'
      elif obj == 'X':
      d_board += 'X'
      elif obj == 'O':
      d_board += 'O'

      if pos%3 == 0:
      d_board += 'n'
      print(d_board)

      def getAvailable(self):
      """
      Returns available positions
      """
      available =
      for pos, obj in self.board.items():
      if obj == None:
      available.append(pos)
      return available

      class Tic_Tac_Toe(Board):
      pieces = ['O', 'X']

      def __init__(self):
      super().__init__()
      self.piece = Tic_Tac_Toe.pieces.pop(random.choice([0,1]))
      self.cp_piece = Tic_Tac_Toe.pieces[0]

      def user_setName(self, name):
      self.name = name

      def user_setPiece(self, position):
      """
      Position parameter denoted by a number on the keypad (1-9)
      """
      self.board[position] = self.piece

      def user_getPiece(self):
      return self.piece

      def cp_setPiece(self):
      self.board[random.choice(self.getAvailable())] = self.cp_piece

      def cp_getPiece(self):
      return self.cp_piece

      def checkWin(self, player):
      """
      Checks if move by either the user or computer results in a win
      """
      def at_least_one(A, B):
      for i in A:
      for j in B:
      if i == j:
      return True
      return False

      win_patterns = [(1,2,3),(4,5,6),(7,8,9),
      (1,4,7),(2,5,8),(3,6,9),
      (3,5,7),(1,5,9)]
      spots = [k for k, v in self.board.items() if v == player]
      spots.sort()
      player_combinations = list(combinations(spots,3))
      if at_least_one(player_combinations, win_patterns) == True:
      return True
      return False

      def checkFullBoard(self):
      if None not in self.board.values():
      self.display()
      print('Draw! Game board full!')
      return True
      return False

      #---------

      def main():
      # Setup game
      game = Tic_Tac_Toe()
      input('Hello user! Welcome to Tic Tac Toe! Press any key to continue')

      if game.user_getPiece() == 'X':
      print('You are X. You are going first.')
      else:
      print('You are O. You are going second.')
      game.cp_setPiece()

      # Main game loop
      while True:
      game.display()
      position = input('Use the number pad on the lefthand side of your keyboardnto select your position (1-9):')

      try:
      position = int(position)
      if position in range(1,10):
      if position in game.getAvailable():
      game.user_setPiece(position)
      else:
      print('----Please input an available position.')
      continue
      else:
      print('----Please input a number between 1 and 9.')

      except ValueError:
      print('----Please input a number.')
      continue

      # FOR USER
      # Check for win
      if game.checkWin(game.user_getPiece()) == True:
      game.display()
      print('Congratulations! You win!')
      break

      # Check for full board
      if game.checkFullBoard() == True:
      break

      # FOR COMPUTER
      game.cp_setPiece()
      # Check for win
      if game.checkWin(game.cp_getPiece()) == True:
      game.display()
      print('Sorry. You lost.')
      break

      # Check for full board
      if game.checkFullBoard() == True:
      break

      if __name__ == '__main__':
      main()









      share|improve this question









      New contributor




      Von Vic Cayas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I made a simply user vs. computer game on Tic Tac Toe. I used Object Oriented Programming to increase my understanding of this programming paradigm. Can you criticize any design flaws I have in my code?



      #!/usr/bin/env python3
      # -*- coding: utf-8 -*-
      """
      Created on Sat Dec 15 20:56:48 2018

      @author: von-vic
      """
      import random
      from itertools import combinations

      class Board(object):

      def __init__(self):
      self.board = {x:None for x in (7,8,9,4,5,6,1,2,3)}

      def display(self):
      """
      Displays tic tac toe board
      """
      d_board = 'nTIC TAC TOE:n'
      for pos, obj in self.board.items():
      if obj == None:
      d_board += '_'
      elif obj == 'X':
      d_board += 'X'
      elif obj == 'O':
      d_board += 'O'

      if pos%3 == 0:
      d_board += 'n'
      print(d_board)

      def getAvailable(self):
      """
      Returns available positions
      """
      available =
      for pos, obj in self.board.items():
      if obj == None:
      available.append(pos)
      return available

      class Tic_Tac_Toe(Board):
      pieces = ['O', 'X']

      def __init__(self):
      super().__init__()
      self.piece = Tic_Tac_Toe.pieces.pop(random.choice([0,1]))
      self.cp_piece = Tic_Tac_Toe.pieces[0]

      def user_setName(self, name):
      self.name = name

      def user_setPiece(self, position):
      """
      Position parameter denoted by a number on the keypad (1-9)
      """
      self.board[position] = self.piece

      def user_getPiece(self):
      return self.piece

      def cp_setPiece(self):
      self.board[random.choice(self.getAvailable())] = self.cp_piece

      def cp_getPiece(self):
      return self.cp_piece

      def checkWin(self, player):
      """
      Checks if move by either the user or computer results in a win
      """
      def at_least_one(A, B):
      for i in A:
      for j in B:
      if i == j:
      return True
      return False

      win_patterns = [(1,2,3),(4,5,6),(7,8,9),
      (1,4,7),(2,5,8),(3,6,9),
      (3,5,7),(1,5,9)]
      spots = [k for k, v in self.board.items() if v == player]
      spots.sort()
      player_combinations = list(combinations(spots,3))
      if at_least_one(player_combinations, win_patterns) == True:
      return True
      return False

      def checkFullBoard(self):
      if None not in self.board.values():
      self.display()
      print('Draw! Game board full!')
      return True
      return False

      #---------

      def main():
      # Setup game
      game = Tic_Tac_Toe()
      input('Hello user! Welcome to Tic Tac Toe! Press any key to continue')

      if game.user_getPiece() == 'X':
      print('You are X. You are going first.')
      else:
      print('You are O. You are going second.')
      game.cp_setPiece()

      # Main game loop
      while True:
      game.display()
      position = input('Use the number pad on the lefthand side of your keyboardnto select your position (1-9):')

      try:
      position = int(position)
      if position in range(1,10):
      if position in game.getAvailable():
      game.user_setPiece(position)
      else:
      print('----Please input an available position.')
      continue
      else:
      print('----Please input a number between 1 and 9.')

      except ValueError:
      print('----Please input a number.')
      continue

      # FOR USER
      # Check for win
      if game.checkWin(game.user_getPiece()) == True:
      game.display()
      print('Congratulations! You win!')
      break

      # Check for full board
      if game.checkFullBoard() == True:
      break

      # FOR COMPUTER
      game.cp_setPiece()
      # Check for win
      if game.checkWin(game.cp_getPiece()) == True:
      game.display()
      print('Sorry. You lost.')
      break

      # Check for full board
      if game.checkFullBoard() == True:
      break

      if __name__ == '__main__':
      main()






      python beginner object-oriented tic-tac-toe






      share|improve this question









      New contributor




      Von Vic Cayas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Von Vic Cayas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 19 mins ago









      200_success

      128k15149412




      128k15149412






      New contributor




      Von Vic Cayas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 1 hour ago









      Von Vic Cayas

      61




      61




      New contributor




      Von Vic Cayas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Von Vic Cayas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Von Vic Cayas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.



























          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
          });


          }
          });






          Von Vic Cayas is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210020%2fbeginners-user-vs-computer-tic-tac-toe%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          Von Vic Cayas is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          Von Vic Cayas is a new contributor. Be nice, and check out our Code of Conduct.













          Von Vic Cayas is a new contributor. Be nice, and check out our Code of Conduct.












          Von Vic Cayas is a new contributor. Be nice, and check out our Code of Conduct.
















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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.


          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%2f210020%2fbeginners-user-vs-computer-tic-tac-toe%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

          Ellipse (mathématiques)

          Quarter-circle Tiles

          Mont Emei