Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TicTacGame:
- player = 'X'
- winner = ''
- board = {'7': ' ', '8': ' ', '9': ' ',
- '4': ' ', '5': ' ', '6': ' ',
- '1': ' ', '2': ' ', '3': ' '}
- def show_board(self):
- print(' | |')
- print(' {} | {} | {}'.format(self.board['7'], self.board['8'], self.board['9']))
- print('_____|_____|_____')
- print(' | |')
- print(' {} | {} | {}'.format(self.board['4'], self.board['5'], self.board['6']))
- print('_____|_____|_____')
- print(' | |')
- print(' {} | {} | {}'.format(self.board['1'], self.board['2'], self.board['3']))
- print(' | |')
- def validate_input(self, turn):
- try:
- move = int(turn)
- except ValueError:
- return 0
- if move > 9 or move < 1:
- return 0
- if self.board[turn] != ' ':
- return 0
- return 1
- def make_turn(self):
- while True:
- print('Player', self.player, 'turn:')
- turn = input()
- if self.validate_input(turn):
- self.board[turn] = self.player
- if self.player == 'X':
- self.player = 'O'
- else:
- self.player = 'X'
- break
- else:
- print('Wrong input! Try again!')
- def check_winner(self):
- winnings = [['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3'],
- ['1', '4', '7'], ['2', '5', '8'], ['3', '6', '9'],
- ['1', '5', '9'], ['3', '5', '7']]
- for comb in winnings:
- if self.board[comb[0]] != ' ':
- if self.board[comb[0]] == self.board[comb[1]] and self.board[comb[0]] == self.board[comb[2]]:
- return 1
- return 0
- def start_game(self):
- turn = 0
- while True:
- self.show_board()
- if turn == 9:
- print('Draw!')
- return
- self.make_turn()
- if self.check_winner():
- self.show_board()
- if self.player == 'X':
- self.winner = 'O'
- else:
- self.winner = 'X'
- print('Player', self.winner, 'has won!!!')
- return
- turn += 1
- if __name__ == '__main__':
- game = TicTacGame()
- game.start_game()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement