Rubykuby

Connect Four

Apr 11th, 2013
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.25 KB | None | 0 0
  1. from random import randint
  2. from copy import deepcopy
  3.  
  4. def printBoard(board):
  5.     rowCounter = 1
  6.     print("-" * 33)
  7.     for i in range(8):
  8.         row = board[i]
  9.         row = " | ".join(row)
  10.         print("| " +row + " | " + str(rowCounter))
  11.         rowCounter += 1
  12.         if rowCounter <= 8:
  13.             print("|" + "-" * 31 + "|")
  14.         if rowCounter == 9:
  15.             print("-" * 33)
  16.             print("  A   B   C   D   E   F   G   H")
  17.            
  18. def choosePlayer():
  19.     player = None
  20.     while player != "X" or player != "O":
  21.         player = input("What letter do you pick? (X or O): ").upper()
  22.         if player == "X":
  23.             computer = "O"
  24.             return player, computer
  25.         elif player == "O":
  26.             computer = "X"
  27.             return player, computer
  28.         else:
  29.             print("Invalid input. Pick either X or O.")
  30.  
  31. def whoStarts(player, computer):
  32.     participantList = [player, computer]
  33.     randInt = randint(0, 1)
  34.     return participantList[randInt]
  35.  
  36. def isColumnFull(board, column):
  37.     counter = 0
  38.     for i in range(8):
  39.         if "_" not in board[i][column]: #Goes vertically downa single column to count absences of "_"
  40.             counter += 1
  41.     if counter == 8: #If eight absences of "_" were found, the column must be full
  42.         return True
  43.     else:
  44.         return False
  45.  
  46. def pickColumn(board, column, participant):
  47.     for i in reversed(range(8)): #Reverses all rows. Bottom ones go first
  48.         if board[i][column] == "_": #So soon as an empty row/column combination is found (column remains constant), returns true
  49.             board[i][column] = participant
  50.             break
  51.  
  52. def isWinner(board):
  53.     for i in range(8):
  54.         row = board[i] #Extracts a single row from the list
  55.         for x in range(5):
  56.             if row[x] == row[x+1] and row[x] == row[x+2] and row[x] == row[x+3] and row[x] != "_": #Horizontal comparison (row)
  57.                 return True
  58.    
  59.     for i in range(5):
  60.         rowCounter = 0    
  61.         while rowCounter <= 7:
  62.             if board[i][rowCounter] == board[i+1][rowCounter] and board[i][rowCounter] == board[i+2][rowCounter] and board[i][rowCounter] == board[i+3][rowCounter] and board[i][rowCounter] != "_": #Vertical comparison (column)
  63.                 return True
  64.             rowCounter += 1
  65.    
  66.     for i in range(5):
  67.         rowCounter = 0
  68.         while rowCounter <= 4:
  69.             if board[i][rowCounter] == board[i+1][rowCounter+1] and board[i][rowCounter] == board[i+2][rowCounter+2] and board[i][rowCounter] == board[i+3][rowCounter+3] and board[i][rowCounter] != "_": #Diagonal comparison (top left to bottom right)
  70.                 return True
  71.             rowCounter += 1
  72.            
  73.     for i in range(3, 8):
  74.         rowCounter = 0
  75.         while rowCounter <= 4:
  76.             if board[i][rowCounter] == board[i-1][rowCounter+1] and board[i][rowCounter] == board[i-2][rowCounter+2] and board[i][rowCounter] == board[i-3][rowCounter+3] and board[i][rowCounter] != "_": #Diagonal comparison (bottom left to top right)
  77.                 return True
  78.             rowCounter += 1
  79.    
  80.     return False
  81.  
  82. def dupBoard(board):
  83.     duplicate = deepcopy(board)
  84.     return duplicate
  85.     #duplicate = []
  86.     #for row in board:
  87.     #    duplicate.append(row) #Fancy way of duplicating. Could use duplicate = board, return duplicate
  88.     #return duplicate
  89.  
  90. def isBoardFull(board):
  91.     for i in range(8):
  92.         for x in range(8): #Checks all possible spots for "_"s. Returns false so soon as one is found
  93.             if board[i][x] == "_":
  94.                 return False
  95.     return True
  96.  
  97. def getComputerChoice(board, computer, player):
  98.     #Can I win? Return that
  99.     for i in range(8):
  100.         duplicate = dupBoard(board)
  101.         if not isColumnFull(duplicate, i):
  102.             pickColumn(duplicate, i, computer)
  103.             if isWinner(duplicate):
  104.                 return i
  105.    
  106.     #Can player win? Return that
  107.     for i in range(8):
  108.         duplicate = dupBoard(board)
  109.         if not isColumnFull(duplicate, i):
  110.             pickColumn(duplicate, i, player)
  111.             if isWinner(duplicate):
  112.                 return i
  113.    
  114.     #Pick any other column (lol stupid AI)
  115.     duplicate = dupBoard(board)
  116.     while True:
  117.         choice = randint(0, 7)
  118.         if not isColumnFull(duplicate, choice):
  119.             return choice
  120.  
  121. def getPlayerChoice(board):
  122.     while True:
  123.         choice = input("Which column do you want to picK? (A-H): ").upper()
  124.         try:
  125.             choice = ord(choice) - 65 #"A" = 0, "H" = 7
  126.             if choice >= 0 and choice <=7:
  127.                 if not isColumnFull(board, choice):
  128.                     return choice
  129.                 else:
  130.                     print("That column is full.")
  131.         except:
  132.             print("That input is invalid.")
  133.  
  134. playAgain = True
  135.  
  136. while playAgain == True:
  137.     board = [["_"] * 8 for i in range(8)]
  138.     gameOver = False
  139.     player, computer = choosePlayer()
  140.    
  141.     turn = whoStarts(player, computer)
  142.    
  143.     while gameOver == False:
  144.         if turn == player:
  145.             printBoard(board)
  146.             choice = getPlayerChoice(board)
  147.             pickColumn(board, choice, player)
  148.            
  149.             if isWinner(board):
  150.                 printBoard(board)
  151.                 print("Congratulations! You have won!")
  152.                 gameOver = True
  153.            
  154.             elif isBoardFull(board):
  155.                 printBoard(board)
  156.                 print("Alas. It is a tie.")
  157.                 gameOver = True
  158.            
  159.             else:
  160.                 turn = computer
  161.        
  162.         if turn == computer:
  163.             choice = getComputerChoice(board, computer, player)
  164.             pickColumn(board, choice, computer)
  165.            
  166.             if isWinner(board):
  167.                 printBoard(board)
  168.                 print("You have failed!")
  169.                 gameOver = True
  170.            
  171.             elif isBoardFull(board):
  172.                 printBoard(board)
  173.                 print("Alas. It is a tie.")
  174.                 gameOver = True
  175.            
  176.             else:
  177.                 turn = player
  178.     playAgain = input("Do you want to play again? (yes or no): ")
  179.     if playAgain.lower().startswith("y"):
  180.         playAgain = True
  181.     else:
  182.         playAgain = False
Advertisement
Add Comment
Please, Sign In to add comment