Advertisement
Guest User

Untitled

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