Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.98 KB | None | 0 0
  1. import random
  2. from tkinter import *
  3.  
  4. class Connect4:
  5.     def __init__(self, rowCount, colCount, circleSize, window):
  6.         self.margin = 25
  7.         self.rowCount = rowCount
  8.         self.colCount = colCount
  9.         self.circleSize = circleSize
  10.         self.circleSpacing = 10
  11.         self.messageSize = 15
  12.         self.width = self.colCount * (self.circleSize + self.circleSpacing)
  13.         self.height = self.rowCount * (self.circleSize + self.circleSpacing) + self.messageSize*4
  14.         self.window = window
  15.         self.data = []
  16.         self.frame = Frame(window)
  17.         self.frame.pack()
  18.         self.diameter = self.circleSize #self.rowCount * self.colCount
  19.         self.initialColor = 'white'
  20.         self.resetButton = Button(self.frame, text='Restart', command=self.restartGame)
  21.         self.resetButton.place(x=340, y=0)
  22.         self.quitButton = Button(self.frame, text='Quit', command=self.quitGame)
  23.         self.quitButton.pack(side=TOP)
  24.         self.draw = Canvas(self.frame, height=self.height, width=self.width)
  25.         self.draw.bind('<Button-1>', self.mouseInput)
  26.         self.circles = []
  27.         self.colors = []
  28.         self.ox = 'X'
  29.         y = self.circleSpacing
  30.         for row in range(self.rowCount):
  31.             circleRow = []
  32.             colorRow = []
  33.             x = self.circleSpacing
  34.             for col in range(self.colCount):
  35.                 circleRow += [self.draw.create_oval(x, y, x + self.diameter, y + self.diameter, fill=self.initialColor)]
  36.                 colorRow += [self.initialColor]
  37.                 x += self.diameter + self.circleSpacing
  38.             self.circles += [circleRow]
  39.             self.colors += [colorRow]
  40.             y += self.diameter + self.circleSpacing
  41.         self.message = self.draw.create_text(self.messageSize, self.height-self.messageSize, text=f'{self.ox}\'s turn!', anchor='w', font='Courier 27')
  42.         for row in range(self.rowCount):
  43.             boardRow = []
  44.             for col in range(self.colCount):
  45.                 boardRow += [' ']
  46.             self.data += [boardRow]
  47.         self.draw.pack(padx = self.margin, pady = self.margin)
  48.  
  49.     def __repr__(self): # Sets the literal structure of the board so that it's easy to interpret for the players
  50.         s = ''
  51.         for row in range(self.height):
  52.             s += '|'
  53.             for col in range(self.width):
  54.                 s += self.data[row][col] + '|'
  55.             s += '\n'
  56.         s += '--'*self.width + '-\n'
  57.         for col in range(self.width):
  58.             s += ' ' + str(col%10)
  59.         s += '\n'
  60.         return s
  61.  
  62.     def mouseInput(self, event):
  63.         col = int(event.x/(self.diameter+self.circleSpacing))
  64.         self.hostGame(aiPlayer)
  65.         self.updateBoard(col)
  66.    
  67.     def quitGame(self):
  68.         self.window.destroy()
  69.  
  70.     def restartGame(self):
  71.         self.clear()
  72.         for row in range(self.rowCount):
  73.             for col in range(self.colCount):
  74.                 self.draw.itemconfig(self.circles[row][col], fill='white')
  75.  
  76.     def clear(self): # Clears the current state of the board
  77.         self.ox = ' '
  78.         for row in range(self.height):
  79.             for col in range(self.width): # For every value in the board
  80.                 self.placeChecker(row, col, 'white')
  81.                 self.data[row][col] = ' ' # Override whatever is there with a space (the original value each spot starts with)
  82.         self.ox = 'X'
  83.  
  84.     def setChecker(self, row, col, color): # Where the user clicked
  85.         self.data[row][col] = self.ox
  86.         self.draw.itemconfig(self.circles[row][col], fill=color)
  87.  
  88.     def setText(self, text):
  89.         self.draw.itemconfig(self.message, text=text)
  90.  
  91.     def lowestRow(self, col):
  92.         if self.allowsMove(col):
  93.             for row in range(self.rowCount):
  94.                 if self.data[row][col] != ' ': # If the spot is not empty...
  95.                     return row - 1
  96.             return self.rowCount - 1
  97.  
  98.     def hostGame(self, aiPlayer):
  99.         if self.winsFor(self.ox):
  100.             # The move they just did let them win
  101.             self.setText(f'{self.ox} won!')
  102.         else:
  103.             O = aiPlayer.nextMove(self.data)
  104.             self.placeChecker(O, color='black')
  105.             self.addMove(O, self.ox)
  106.             #self.ox = 'O' if self.ox == 'X' else 'X'
  107.             self.setText(f'{self.ox}\'s turn!')
  108.  
  109.     def placeChecker(self, col, color = None):
  110.         if color is None:
  111.             color = 'red' if self.ox == 'X' else 'black'
  112.         row = self.lowestRow(col)
  113.         self.setChecker(row, col, color)
  114.  
  115.     def updateBoard(self, col): # Adds a "checker" to the column passed
  116.         self.placeChecker(col)
  117.         self.addMove(col, self.ox)
  118.  
  119.     def addMove(self, col, ox):
  120.         if self.allowsMove(col): # Uses allowsMove to check if the column is available
  121.             for row in range(self.rowCount):
  122.                 if self.data[row][col] != ' ': # If the spot is not empty...
  123.                     self.data[row-1][col] = ox # Add the checker to the spot above it
  124.                     return
  125.             self.data[self.rowCount-1][col] = ox # Otherwise but the checker there
  126.  
  127.     def allowsMove(self, col): # Tests to see if a column has room for another move
  128.         if 0 <= col < self.colCount:
  129.             return self.data[0][col] == ' '
  130.         else:
  131.             return False
  132.  
  133.     def delMove(self, col): # Deletes the last move played in column passed to the function
  134.         for row in range(self.rowCount): # For each row..
  135.             if self.data[row][col] != ' ': # If the indexed spot is not empty
  136.                 self.data[row][col] = ' ' # Override whatever is there with a space
  137.                 return
  138.         return
  139.  
  140.     def isFull(self): # Checks if the board is full or not
  141.         for values in self.data: # For each value in the entire board, if there's a space anywhere then it's not full (False). If there isn't a space, then the board is full (True).
  142.             if ' ' in values:
  143.                 return False
  144.         return True
  145.  
  146.     def winsFor(self, ox): # Checks to see if a checker ('X' or 'O') won the Connect 4.
  147.         for row in range(self.rowCount): # Horizontal check
  148.             for col in range(self.colCount - 3): # Uses an anchor point (subtracting 3 from the width and so forth) from where to start checking so it doesn't go out of range.
  149.                 if self.data[row][col] == ox and self.data[row][col+1] == ox and self.data[row][col+2] == ox and self.data[row][col+3] == ox:
  150.                     return True
  151.         for row in range(self.rowCount - 3): # Vertical check
  152.             for col in range(self.colCount):
  153.                 if self.data[row][col] == ox and self.data[row+1][col] == ox and self.data[row+2][col] == ox and self.data[row+3][col] == ox:
  154.                     return True
  155.         for row in range(self.rowCount - 3): # SW>NE check
  156.             for col in range(self.colCount - 3):
  157.                 if self.data[row][col] == ox and self.data[row+1][col+1] == ox and self.data[row+2][col+2] == ox and self.data[row+3][col+3] == ox:
  158.                     return True
  159.         for row in range(3, self.rowCount): # SE>NW check
  160.             for col in range(self.colCount - 3):
  161.                 if self.data[row][col] == ox and self.data[row-1][col+1] == ox and self.data[row-2][col+2] == ox and self.data[row-3][col+3] == ox:
  162.                     return True
  163.         return False
  164. """
  165.    def hostGame(self): # Makes the game more playable by asking the user their turn and checking for wins or ties automatically
  166.        move = 0 # This is used later so it will rotate back and forth between asking X to move and asking O to move
  167.        while self.isFull() == False and self.winsFor('OX') != True: # While the board is not full and nobody has won yet, continue the loop
  168.            if move == 0: # When move is 0, it's X's turn (X always goes first)
  169.                X = int(input('Player "X", what column would you like to move? ')) # Asks for the user's input for which column to move, then turns it into an integer and stores it in X
  170.                if self.allowsMove(X): # If that position is allowed...
  171.                    self.addMove(X, 'X') # Add that move for 'X'
  172.                    move += 1 # Increment move by 1 so that move won't be 0, and thus it will be O's turn
  173.                    if self.winsFor('X'): # Check to see if X won the game with that move
  174.                        print('Congratulations Player "X", you win!')
  175.                        return
  176.                else:
  177.                    while self.allowsMove(X) == False: # While the user keeps putting invalid columns...
  178.                        X = int(input('Oops! Your response was invalid, try again: ')) # Keep asking until the user chooses a column that is allowed
  179.                    self.addMove(X, 'X')
  180.                    move += 1
  181.                    if self.winsFor('X'):
  182.                        print('Congratulations Player "X", you win!')
  183.                        return
  184.            else: # O's turn to play, same mechanics just for a different player
  185.                O = int(input('Player "O", what column would you like to move? '))
  186.                if self.allowsMove(O):
  187.                    self.addMove(O, 'O')
  188.                    move -= 1 # Decrements move so it will be 0 and thus will be X's turn again
  189.                    if self.winsFor('O'):
  190.                        print('Congratulations Player "O", you win!')
  191.                        return
  192.                else:
  193.                    while self.allowsMove(O) == False:
  194.                        O = int(input('Oops! Your response was invalid, try again: '))
  195.                    move -= 1
  196.                    self.addMove(O, 'O')
  197.                    if self.winsFor('O'):
  198.                        print('Congratulations Player "O", you win!')
  199.                        return
  200.        print('It\'s a tie!') # If it breaks out of the loop and someone hasn't already won, then that mean the board must be full and thus would be a tie
  201.        return
  202. """
  203. """
  204.    def playGameWith(self, aiPlayer):
  205.        move = 0 # This is used later so it will rotate back and forth between asking X to move and asking O to move
  206.        while self.isFull() == False and self.winsFor('OX') != True: # While the board is not full and nobody has won yet, continue the loop
  207.            if move == 0: # When move is 0, it's X's turn (X always goes first)
  208.                print(b)
  209.                X = int(input('Player "X", what column would you like to move? ')) # Asks for the user's input for which column to move, then turns it into an integer and stores it in X
  210.                if self.allowsMove(X): # If that position is allowed...
  211.                    self.addMove(X, 'X') # Add that move for 'X'
  212.                    move += 1 # Increment move by 1 so that move won't be 0, and thus it will be O's turn
  213.                    if self.winsFor('X'): # Check to see if X won the game with that move
  214.                        print('Congratulations Player "X", you win!')
  215.                        return
  216.                else:
  217.                    while self.allowsMove(X) == False: # While the user keeps putting invalid columns...
  218.                        X = int(input('Oops! Your response was invalid, try again: ')) # Keep asking until the user chooses a column that is allowed
  219.                    self.addMove(X, 'X')
  220.                    move += 1
  221.                    if self.winsFor('X'):
  222.                        print('Congratulations Player "X", you win!')
  223.                        return
  224.            else: # O's turn to play, same mechanics just for a different player
  225.                print(b)
  226.                O = aiPlayer.nextMove()
  227.                self.addMove(O, 'O')
  228.                move -= 1 # Decrements move so it will be 0 and thus will be X's turn again
  229.                if self.winsFor('O'):
  230.                    print('Congratulations Player "O", you win!')
  231.                    return
  232.        print('It\'s a tie!') # If it breaks out of the loop and someone hasn't already won, then that mean the board must be full and thus would be a tie
  233.        return
  234. """
  235. class Player:
  236.     def __init__(self, ox, tbt, ply):
  237.         self.ox = ox
  238.         self.tbt = tbt
  239.         self.ply = ply
  240.  
  241.     def __repr__(self):
  242.         intro = 'Tiebreak Type' + self.tbt
  243.         intro += '\n' + 'Ply:' + str(self.ply)
  244.         return intro
  245.  
  246.     def opponent(self):
  247.         if self.ox == 'X':
  248.             return 'O'
  249.         else:
  250.             return 'X'
  251.  
  252.     def scoreBoard(self, b):
  253.         if b.winsFor(self.opponent()) == True:
  254.             return 0
  255.         elif b.winsFor(self.ox) == True:
  256.             return 100
  257.         else:
  258.             return 50
  259.  
  260.     def tieBreakType(self, scores):
  261.         eachCol = []
  262.         t = 0
  263.         for col in range(len(scores)):
  264.             if scores[col] == max(scores):
  265.                 t += 1
  266.                 eachCol += [col]
  267.         if t > 1:
  268.             if self.tbt == 'Random':
  269.                 return random.choice(eachCol)
  270.             elif self.tbt == 'Right':
  271.                 return max(eachCol)
  272.             elif self.tbt == 'Left':
  273.                 return min(eachCol)
  274.         else:
  275.             return eachCol[0]
  276.  
  277.     def scoresFor(self, b, ox, ply):
  278.         score = [50]*7 # Pre-seeds a list with the default value of 50, uses list multiplication to get the width of the board to determine how many columns are needed
  279.         for col in range(7): # For each column...
  280.             if b.allowsMove(col) == False: # Base Case, if the column is full it should always have the value of -1
  281.                 score[col] = -1
  282.             elif b.winsFor(self.opponent()) or b.winsFor(self.ox): # Base Case, the column is either valued as a loss (0) or a win(100)
  283.                 score[col] = self.scoreBoard(b)
  284.             elif self.ply == 0: # Base Case, ply 0 will always value every column (except full columns) at 50
  285.                 score[col] = 50
  286.             elif self.ply > 0: # Evaluates higher plys through recursion
  287.                 b.addMove(col, self.ox) # Add a move to every column and evaluate
  288.                 if self.scoreBoard == 0 or self.scoreBoard == 100: # Evaluate if the scoreBoard is a loss or a win
  289.                     score[col] = self.scoreBoard(b)
  290.                 else:
  291.                     p = Player(self.opponent(), self.tbt, self.ply-1) # Sets up the parameters of the game, subtracts 1 from ply to avoid loop
  292.                     score[col] = 100 - max(p.scoresFor(b, self.ox, self.ply)) # This is the recursive step that uses scoresFor to evaluate the board based on the opponent, tiebreak type, and ply number.
  293.                 b.delMove(col) # Delete the move from every column after done evaluating
  294.         return score # Return the best decision(s)
  295.  
  296.     def nextMove(self, b):
  297.         score = self.scoresFor(b, self.ox, self.ply)
  298.         return self.tieBreakType(score)
  299.  
  300. root = Tk()
  301. root.title('Connect 4')
  302. game = Connect4(6, 7, 100, root)
  303. aiPlayer = Player('O', 'Random', 3)
  304. game.hostGame(aiPlayer)
  305. root.mainloop()
  306.  
  307. def main():
  308.     pass
  309.  
  310. if __name__ == '__main__':
  311.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement