Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Field:
- val = " "
- pos = 0
- weight = 0
- def __init__(self, n):
- self.pos = n
- self.val = str(n)
- def display_board(b):
- br = 1
- for i in b:
- if br >= 3:
- print("[", i.val, "]", end='n')
- br = 0
- else:
- print("[", i.val, "]", end='')
- br += 1
- def did_player_won(b, t):
- indexes = (
- (0, 1, 2), (3, 4, 5), (6, 7, 8), # Rows
- (0, 3, 6), (1, 4, 7), (2, 5, 8), # Cols
- (0, 4, 8), (2, 4, 6) # Diag
- )
- for idx in indexes:
- if sum(b[i].weight for i in idx if b[i].val == t) == 15:
- return True
- def get_move(b, turn):
- # Get user input while it's wrong
- while True:
- try:
- move = int(input("Player %s turn!n>>>" % turn))
- # if input isn't an integer
- except ValueError:
- print("Wrong field!")
- continue
- else:
- if 0 < move < 10:
- for item in b:
- if item.pos == move:
- # Check if place is taken
- if item.val == "X" or item.val == "O":
- print("Field is taken!")
- continue
- else:
- item.val = turn
- item.weight = 5
- print("Player %s took place %d" % (turn, move))
- return True
- else:
- print("Incorrect field!")
- continue
- def next_turn(currentturn):
- if currentturn == "X":
- return "O"
- else:
- return "X"
- def reset_game():
- global board
- global turn
- global turns
- board = [Field(7), Field(8), Field(9),
- Field(4), Field(5), Field(6),
- Field(1), Field(2), Field(3)]
- turn = "X"
- turns = 0
- board = [Field(7), Field(8), Field(9),
- Field(4), Field(5), Field(6),
- Field(1), Field(2), Field(3)]
- turn = "X"
- turns = 0
- moveMessage = "Player (%s) move: " % turn
- while True:
- display_board(board)
- if turns >= 9:
- display_board(board)
- print("Draw!")
- choice = input(">>>")
- if choice == "play":
- reset_game()
- else:
- break
- if get_move(board, turn):
- if did_player_won(board, turn):
- display_board(board)
- print("Player %s won! Congrats Comrade! It's OUR win!" % turn)
- choice = input(">>>")
- if choice == "play":
- reset_game()
- else:
- break
- else:
- turn = next_turn(turn)
- turns += 1
Add Comment
Please, Sign In to add comment