Advertisement
Guest User

Untitled

a guest
Jan 16th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.69 KB | None | 0 0
  1. HEIGHT = 6
  2. WIDTH = 7
  3.  
  4. def initialize():
  5. ''' Sets up the empty board. '''
  6. board = []
  7. for i in range(HEIGHT):
  8. board.append(["O"] * WIDTH)
  9. return board
  10.  
  11. def print_board(board):
  12. ''' Prints out a correct formatted board. '''
  13. print("")
  14. print("1 2 3 4 5 6 7")
  15. print("_" * 13)
  16. for row in board:
  17. print("|".join(row))
  18.  
  19. def get_move(board, player):
  20. ''' Takes the board and the player as parameter. Asks the player to input a
  21. column and checks if the entry is valid. '''
  22. col = int(input("Player {} enter a column: ".format(player)))
  23. if col > WIDTH or col < 1:
  24. print("Invalid input. Enter a number between 1 and 7.")
  25. col = get_move(board, player)
  26.  
  27. col = col - 1
  28.  
  29. col_full = True
  30. for i in range(HEIGHT):
  31. if board[i][col] == "O":
  32. col_full = False
  33. break
  34. if col_full:
  35. print("That column is full. Try again.")
  36. col = get_move(board, player)
  37. return col
  38.  
  39. def make_move(board, player, col):
  40. ''' Takes the board, the player, and the player's entry and makes the move based
  41. on the board configuration and the entry. '''
  42. row = 0
  43. for i in range(HEIGHT):
  44. if board[i][col] == "O":
  45. row = i
  46. else:
  47. break
  48.  
  49. board[row][col] = player
  50. return board
  51.  
  52. def check_win(board):
  53. ''' This function takes the board as a parameter and checks if someone has won
  54. the game. If so, it returns the player that has won. Otherwise, it returns
  55. an empty string. '''
  56. for row in range(HEIGHT):
  57. for col in range(WIDTH - 3):
  58. if (board[row][col] == board[row][col+1] == board[row][col+2] == board[row][col+3]) and board[row][col] != "O":
  59. return board[row][col]
  60.  
  61. for col in range(WIDTH):
  62. for row in range(HEIGHT - 3):
  63. if (board[row][col] == board[row+1][col] == board[row+2][col] == board[row+3][col]) and board[row][col] != "O":
  64. return board[row][col]
  65.  
  66. return ""
  67.  
  68. def main():
  69. ''' Sets up the game and runs the game loop until the game is over. '''
  70. board = initialize()
  71. player = "A"
  72. winner = ""
  73.  
  74. while winner == "":
  75. print_board(board)
  76. col = get_move(board, player)
  77. board = make_move(board, player, col)
  78. winner = check_win(board)
  79. #if player == "A": player = "B"
  80. #else: player = "A"
  81. player = "B" if player == "A" else "A"
  82.  
  83. print_board(board)
  84. if winner == "Tie":
  85. print("Tie.")
  86. else:
  87. print("Player {} wins".format(winner))
  88.  
  89. if __name__ == "__main__":
  90. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement