Advertisement
Guest User

Untitled

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