Advertisement
Guest User

tic tac toe

a guest
May 1st, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. def print_board(board):
  2.  
  3. print ("The board will look like this:")
  4.  
  5. for i in range(1):
  6. for i in range (10):
  7. print(i, end = "")
  8. print("|", end = "")
  9. if i % 3 == 0:
  10. print()
  11.  
  12.  
  13. def print_instruction():
  14. print ("Yo player!! Please use the following cell numbers to make your move")
  15. print_board([2,3,4,5,6,7,8,9,10])
  16.  
  17.  
  18. def get_input(turn):
  19.  
  20. valid = False
  21. while not valid:
  22. try:
  23. user =(input("Player!! Where would you like to place " + turn + " (1-9)? "))
  24. user = int(user)
  25. if user >= 1 and user <= 9:
  26. return user-1
  27. else:
  28. print ("Payer!! That is not a valid move! Please try again.\n")
  29. print_instruction()
  30. except Exception as e:
  31. print(user + ("Player that is not a valid move! Please try again.\n"))
  32.  
  33. def check_win(board):
  34. win_cond = ((1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),(3,5,7))
  35. for each in win_cond:
  36. try:
  37. if board[each[0]-1] == board[each[1]-1] and board[each[1]-1] == board[each[2]-1]:
  38. return board[each[0]-1]
  39. except:
  40. pass
  41. return -1
  42.  
  43. def quit_game(board,msg):
  44. print_board(board)
  45. print (msg)
  46. quit()
  47.  
  48. def main():
  49.  
  50. ## Start Game
  51. # Change turns
  52. # Checks for winner
  53. # Quits and redo board
  54.  
  55. print_instruction()
  56.  
  57. board = []
  58. for i in range(9):
  59. board.append(-1)
  60.  
  61. print_board(board)
  62.  
  63.  
  64. win = False
  65. move = 0
  66. while not win:
  67.  
  68. # Print board
  69. print_board(board)
  70. print ("Turn number: " + str(move+1))
  71. if move % 2 == 0:
  72. turn = 'K'
  73. else:
  74. turn = 'A'
  75.  
  76. # Get player input
  77. user = get_input(turn)
  78. while board[user] != -1:
  79. print ("Invalid move! Cell already taken. Please try again.\n")
  80. user = get_input(turn)
  81. board[user] = 1 if turn == 'K' else 0
  82.  
  83. # Continue move and check if end of game
  84. move += 1
  85. if move > 4:
  86. winner = check_win(board)
  87. if winner != -1:
  88. out = "The winner is "
  89. out += "Kelly" if winner == 1 else "Andy"
  90. out += ""
  91. quit_game(board,out)
  92. elif move == 9:
  93. quit_game(board,"No winner")
  94.  
  95. if __name__ == "__main__":
  96. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement