Illegal Game Move Checker

Implement a class for a simple game that raises custom exceptions for illegal moves. The game is a simple game of Tic-Tac-Toe.

Example 1:

Input: Current game state: ['X', 'O', 'X', 'O', 'X', 'O', ' ', ' ', ' '], Move: 2 
Output: "Error: Illegal move."

Example 2:

Input: Current game state: ['X', 'O', 'X', 'O', 'X', 'O', ' ', ' ', ' '], Move: 6 
Output: "Move made successfully."

Represent the game state as a list, with each element representing a cell in the game board.

class TicTacToe:
    def __init__(self, state):
        self.state = state

    def make_move(self, cell):
        if self.state[cell] != ' ':
            raise Exception("Error: Illegal move.")
        else:
            self.state[cell] = 'X'
            return "Move made successfully."

game = TicTacToe(['X', 'O', 'X', 'O', 'X', 'O', ' ', ' ', ' '])
print(game.make_move(2))  # Output: "Error: Illegal move."
print(game.make_move(6))  # Output: "Move made successfully."

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!