Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TicTacToe:
- X = 'X'
- O = 'O'
- def __init__(self):
- self.board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
- self.player1_turn = None
- self.player2_turn = None
- self.turn = self.X
- self.game_over = False
- def display_board(self):
- print(f'{self.board[0]} | {self.board[1]} | {self.board[2]}')
- print('---------')
- print(f'{self.board[3]} | {self.board[4]} | {self.board[5]}')
- print('---------')
- print(f'{self.board[6]} | {self.board[7]} | {self.board[8]}')
- def is_legal(self, move):
- if self.board[move] == ' ':
- return True
- else:
- print('This side is not empty!')
- return False
- def piece_p_1(self):
- if self.turn == self.X:
- self.player1_turn = self.X
- else:
- self.player1_turn = self.O
- return self.player1_turn
- def piece_p_2(self, player):
- if player == self.X:
- self.player2_turn = self.X
- else:
- self.player2_turn = self.O
- return self.player2_turn
- def set_player1(self, index):
- try:
- while (index > 8 or index < 0) and not self.is_legal(index):
- print('Input not correct!!!')
- print('Player 1 (0 - 8): ')
- index = int(input())
- else:
- self.board[index] = self.player1_turn
- except:
- print('ERROR')
- def set_player2(self, index):
- try:
- while (index > 8 or index < 0) and not self.is_legal(index):
- print('Input not correct!!!')
- print('Player 2 (0 - 8): ')
- index = int(input())
- else:
- self.board[index] = self.player2_turn
- except:
- print('ERROR')
- def game_loop(self):
- while True:
- p1 = self.piece_p_1()
- p2 = self.piece_p_2(p1)
- self.display_board()
- if p1 == self.X:
- print('Player 1 is first (0 - 8): ')
- index = int(input())
- self.set_player1(index)
- else:
- print('Player 2 is first (0 - 8): ')
- index = int(input())
- self.set_player2(index)
- if self.turn == self.X:
- self.turn = self.O
- else:
- self.turn = self.X
- game = TicTacToe()
- game.game_loop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement