Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.37 KB | None | 0 0
  1.  
  2.  
  3. import random
  4.  
  5.  
  6. class Board:
  7.     """A data type representing a Connect-4 board
  8.       with an arbitrary number of rows and columns.
  9.    """
  10.  
  11.     def __init__(self, width, height):
  12.         """Construct objects of type Board, with the given width and height."""
  13.         self.width = width
  14.         self.height = height
  15.         self.data = [[' ']*width for row in range(height)]
  16.  
  17.     def __repr__(self):
  18.         """This method returns a string representation
  19.           for an object of type Board.
  20.        """
  21.         s = ''
  22.         for row in range(0, self.height):
  23.             s += '|'
  24.             for col in range(0, self.width):
  25.                 s += self.data[row][col] + '|'
  26.             s += '\n'
  27.  
  28.         s += (2*self.width + 1) * '-'
  29.         s += "\n"
  30.         for i in range(0, self.width):
  31.             s += " " + str(i)
  32.  
  33.  
  34.         return s
  35.  
  36.     def addMove(self, col, ox):
  37.         """Adds a checker (O or X) to the column indicated by col.
  38.        """
  39.         H = self.height
  40.         for row in range(0, H):
  41.             if self.data[row][col] != ' ':
  42.                 self.data[row - 1][col] = ox
  43.                 return
  44.         self.data[H - 1][col] = ox
  45.  
  46.     def setBoard(self, moveString):
  47.         """Accepts a string of columns and places
  48.           alternating checkers in those columns,
  49.           starting with 'X'.
  50.  
  51.           For example, call b.setBoard('012345')
  52.           to see 'X's and 'O's alternate on the
  53.           bottom row, or b.setBoard('000000') to
  54.           see them alternate in the left column.
  55.  
  56.           moveString must be a string of one-digit integers.
  57.        """
  58.         nextChecker = 'X'  
  59.         for colChar in moveString:
  60.             col = int(colChar)
  61.             if 0 <= col <= self.width:
  62.                 self.addMove(col, nextChecker)
  63.             if nextChecker == 'X':
  64.                 nextChecker = 'O'
  65.             else:
  66.                 nextChecker = 'X'
  67.  
  68.     def clear(self):
  69.         """Clears the board of all x's amd o's.
  70.        """
  71.         W = self.width
  72.         H = self.height
  73.         self.data = [[' ']*W for row in range(H)]
  74.  
  75.     def allowsMove(self, c):
  76.         """ returns true if the board allows a move in the column (c) specified and returns false if the column is full or not in the board range.
  77.        """
  78.         H = self.height
  79.         W = self.width
  80.         D = self.data
  81.  
  82.         if c >= W or c < 0:
  83.             return False
  84.         elif D[0][c] != ' ':
  85.             return False
  86.         else:
  87.             return True
  88.  
  89.     def isFull(self):
  90.         """ returns true if the board is full of checkers and false if it has open spaces.
  91.        """
  92.         for i in range(self.width):
  93.             if self.allowsMove(i) == True:
  94.                 return False
  95.         return True
  96.  
  97.     def delMove(self, c):
  98.         """removes the top checker from the column c and does nothing if this space is empty.
  99.        """
  100.         H = self.height
  101.         for row in range(0, H):
  102.             if self.data[row][c] != ' ':
  103.                 self.data[row][c] = ' '
  104.                 return
  105.  
  106.     def winsFor(self, ox):
  107.         """Returns true if there are four checkers of type ox in a row on the board and returns false otherwise.
  108.        """
  109.         H = self.height
  110.         W = self.width
  111.         D = self.data
  112.  
  113.         for row in range(0, H):
  114.             for col in range(0, W - 3):
  115.                 if D[row][col] == ox and \
  116.                    D[row][col + 1] == ox and \
  117.                    D[row][col + 2] == ox and \
  118.                    D[row][col + 3] == ox:
  119.                     return True
  120.         for col in range(0, W):
  121.             for row in range(0, H - 3):
  122.                 if D[row][col] == ox and \
  123.                    D[row + 1][col] == ox and \
  124.                    D[row + 2][col] == ox and \
  125.                    D[row + 3][col] == ox:
  126.                     return True
  127.         for row in range(0, H - 3):
  128.             for col in range(0, W - 3):
  129.                 if D[row][col] == ox and \
  130.                    D[row + 1][col + 1] == ox and \
  131.                    D[row + 2][col + 2] == ox and \
  132.                    D[row + 3][col + 3] == ox:
  133.                     return True
  134.         for row in range(0, H - 3):
  135.             for col in range(0, W):
  136.                 if D[row][col] == ox and \
  137.                    D[row + 1][col - 1] == ox and \
  138.                    D[row + 2][col - 2] == ox and \
  139.                    D[row + 3][col - 3] == ox:
  140.                     return True
  141.    
  142.     def colsToWin(self, ox):
  143.         """Returns a list of columns in numeric order where the checker "ox" can move in the next turn in order to win the game, only looking ahead one turn.
  144.        """
  145.         W = self.width
  146.         win = []
  147.         for c in range(W):
  148.             if self.allowsMove(c) == True:
  149.                 self.addMove(c, ox)
  150.                 if self.winsFor(ox) == True:
  151.                     win += [c]
  152.                 self.delMove(c)
  153.         return win
  154.  
  155.  
  156.     def aiMove(self, ox):
  157.         """Returns an integer of what column to move into for the checker "ox" which will be the column that allows ox to win or block the other player if possible or move randomly otherwise.
  158.        """
  159.         if ox == 'O':
  160.             xo = 'X'
  161.         else:
  162.             xo = 'O'
  163.         oxcol = self.colsToWin(ox)
  164.         xocol = self.colsToWin(xo)
  165.         ALL = [ e for e in range( self.width ) if self.allowsMove( e ) ]
  166.  
  167.         if len(oxcol) != 0:
  168.             return oxcol[ 0 ]
  169.         elif len(xocol) != 0:
  170.             return xocol[ 0 ]
  171.         else:
  172.             return random.choice(range(self.width))
  173.            
  174.  
  175.     def hostGame(self):
  176.         """Hosts a game of connect-four, alternating turns between X's and O's (always goes second) and asks the user to select a column number for each move.
  177.        """
  178.         print(self)
  179.         while True:
  180.             x_turn = int(input('Enter your column number for X: '))
  181.             while self.allowsMove(x_turn) ==  False:
  182.                 x_turn = int(input("Enter your column number for X: "))
  183.             self.addMove(x_turn, 'X')
  184.             print(self)
  185.             if self.winsFor('X') == True:
  186.                 print("X wins!")
  187.                 break
  188.  
  189.             y_turn = self.aiMove("O")
  190.             self.addMove(y_turn, 'O')
  191.             print(self)
  192.             if self.winsFor('O') == True:
  193.                 print("O wins!")
  194.                 break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement