Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def switch_turn(turn):
- if turn == "X":
- return "O"
- else:
- return "X"
- def printboard(board):
- print()
- print(board[1] + " | " + board[2] + " | " +board[3])
- print("- + - + -")
- print(board[4] + " | " + board[5] + " | " +board[6])
- print("- + - + -")
- print(board[7] + " | " + board[8] + " | " +board[9])
- print()
- def get_input(turn, board):
- while True:
- print(turn + "'s turn")
- position = input("Enter the position you want to play: ")
- if not position.isdigit(): # what if user enters something that is not a number?
- print("Please enter a number. ")
- elif not 1 <= int(position) <= 9:
- print("Enter a number in the valid range.")
- elif not board[int(position)].isdigit():
- print("Position already taken, please try another position.")
- else:
- return int(position)
- def checkwin(board):
- if board[1] == board[2] == board[3]:
- return True, board[3]
- elif board[4] == board[5] == board[6]:
- return True, board[6]
- elif board[7] == board[8] == board[9]:
- return True, board[9]
- elif board[1] == board[4] == board[7]:
- return True, board[7]
- elif board[2] == board[5] == board[8]:
- return True, board[5]
- elif board[3] == board[6] == board[9]:
- return True, board[9]
- elif board[1] == board[5] == board[9]:
- return True, board[9]
- elif board[3] == board[5] == board[7]:
- return True, board[7]
- else:
- return False, None
- def main():
- turn = "X"
- board = ["0", "1","2", "3","4", "5","6", "7","8", "9"]
- printboard(board)
- game_over = False
- count = 0
- while not game_over and count < 9:
- position = get_input(turn, board)
- count += 1
- board[position] = turn
- printboard(board)
- game_over, winner = checkwin(board)
- turn = switch_turn(turn)
- print(winner, "won the game")
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement