Ad
Code
Diff
  • PLAYER_1 = 1
    PLAYER_2 = 2
    
    
    class NoughtsAndCrosses(object):
        """Basic implementation of Noughts and Crosses"""
        WIN_COMBOS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
        EMPTY_BOARD = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    
        def __init__(self):
            self.current_board = self.EMPTY_BOARD.copy()
            self.current_player = PLAYER_1  # game always starts with PLAYER_1
            self.player_names = {}
            self.location_lists = {
                PLAYER_1: [],
                PLAYER_2: []
            }
            self.player_markers = {
                PLAYER_1: "X",
                PLAYER_2: "O",
            }
        
        def _print_board(self):
            """Prints the current board"""
            print("--- Noughts and Crosses ---")
            print(f'{self.current_board[0]} : {self.current_board[1]} : {self.current_board[2]}')
            print("..........")
            print(f'{self.current_board[3]} : {self.current_board[4]} : {self.current_board[5]}')
            print("..........")
            print(f'{self.current_board[6]} : {self.current_board[7]} : {self.current_board[8]}')
        
        def play(self):
            self._print_welcome_message()
            self._get_player_names()
            while True:
                self._let_current_player_move()
                if self._player_has_won(self.current_player):
                    print(f"{self.player_names[self.current_player]}, you have won!")
                    break
                elif self._check_if_board_is_full():
                    print(f"Stalemate - End of game")
                    break
                self._switch_current_player()
    
        def _let_current_player_move(self):
            print("Hi", self.player_names[self.current_player])
            while True:
                chosen_board_index = self._get_next_move()
                if self._location_is_taken(chosen_board_index):
                    print('>>> Position taken, try again!')
                    continue
                else:
                    self._update_board_and_location_lists(chosen_board_index)
                    self._print_board()
                    break
    
        def _update_board_and_location_lists(self, chosen_board_index):
            self.current_board[chosen_board_index] = self.player_markers[self.current_player]
            self.location_lists[self.current_player].append(chosen_board_index)
    
        @staticmethod
        def _print_welcome_message():
            print("*" * 50)
            print("Welcome to our Noughts and Crosses Game!")
            print("*" * 50)
    
        def _get_player_names(self):
            self.player_names[1] = input("Enter the name of the first player:\n> ")
            self.player_names[2] = input("Enter the name of the second player:\n> ")
    
        def _switch_current_player(self):
            if self.current_player == PLAYER_1:
                self.current_player = PLAYER_2
            else:
                self.current_player = PLAYER_1
    
        def _location_is_taken(self, board_index):
            return self.current_board[board_index] in self.player_markers.values()
    
        def _check_if_board_is_full(self):
            return True if len(self.location_lists[PLAYER_1] + self.location_lists[PLAYER_2]) == 9 else False
    
        def _player_has_won(self, player):
            for win_combo in self.WIN_COMBOS:
                if set(win_combo) <= set(self.location_lists[player]):
                    return True
            return False  # if no winning combinations was found
    
        @staticmethod
        def _get_next_move():
            while True:
                chosen_location = input("Cross location(choose 1 - 9):\n> ")
                if not chosen_location.isdigit() or int(chosen_location) not in range(10):
                    print('>>> Invalid input!')
                    continue
                else:
                    chosen_location = int(chosen_location) - 1  # adjust for array index to start at 0 not 1
                    return chosen_location
    
    
    if __name__ == '__main__':
        NoughtsAndCrosses().play()
    
    • PLAYER_1 = 1
    • PLAYER_2 = 2
    • class NoughtsAndCrosses(object):
    • """Basic implementation of Noughts and Crosses"""
    • WIN_COMBOS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
    • EMPTY_BOARD = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    • def __init__(self):
    • self.current_board = self.EMPTY_BOARD.copy()
    • self.current_player = PLAYER_1 # game always starts with PLAYER_1
    • self.player_names = {}
    • self.location_lists = {
    • PLAYER_1: [],
    • PLAYER_2: []
    • }
    • self.player_markers = {
    • PLAYER_1: "X",
    • PLAYER_2: "O",
    • }
    • def _print_board(self):
    • """Prints the current board"""
    • print("--- Noughts and Crosses ---")
    • print(f'{self.current_board[0]} : {self.current_board[1]} : {self.current_board[2]}')
    • print("..........")
    • print(f'{self.current_board[3]} : {self.current_board[4]} : {self.current_board[5]}')
    • print("..........")
    • print(f'{self.current_board[6]} : {self.current_board[7]} : {self.current_board[8]}')
    • def play(self):
    • self._print_welcome_message()
    • self._get_player_names()
    • while True:
    • self._let_current_player_move()
    • if self._player_has_won(self.current_player):
    • print(f"{self.player_names[self.current_player]}, you have won!")
    • break
    • elif self._check_if_board_is_full():
    • print(f"Stalemate - End of game")
    • break
    • self._switch_current_player()
    • def _let_current_player_move(self):
    • print("Hi", self.player_names[self.current_player])
    • while True:
    • chosen_board_index = self._get_next_move()
    • if self._location_is_taken(chosen_board_index):
    • print('>>> Position taken, try again!')
    • continue
    • else:
    • self._update_board_and_location_lists(chosen_board_index)
    • self._print_board()
    • break
    • def _update_board_and_location_lists(self, chosen_board_index):
    • self.current_board[chosen_board_index] = self.player_markers[self.current_player]
    • self.location_lists[self.current_player].append(chosen_board_index)
    • @staticmethod
    • def _print_welcome_message():
    • print("*" * 50)
    • print("Welcome to our Noughts and Crosses Game!")
    • print("*" * 50)
    • def _get_player_names(self):
    • self.player_names[1] = input("Enter the name of the first player:\n> ")
    • self.player_names[2] = input("Enter the name of the second player:\n> ")
    • def _switch_current_player(self):
    • if self.current_player == PLAYER_1:
    • self.current_player = PLAYER_2
    • else:
    • self.current_player = PLAYER_1
    • def _location_is_taken(self, board_index):
    • return self.current_board[board_index] in self.player_markers.values()
    • def _check_if_board_is_full(self):
    • return True if len(self.location_lists[PLAYER_1] + self.location_lists[PLAYER_2]) == 9 else False
    • def _player_has_won(self, player):
    • for win_combo in self.WIN_COMBOS:
    • if set(win_combo) <= set(self.location_lists[player]):
    • return True
    • return False # if no winning combinations was found
    • @staticmethod
    • def _get_next_move():
    • while True:
    • chosen_location = input("Cross location(choose 1 - 9):\n> ")
    • if not chosen_location.isdigit() or int(chosen_location) not in range(10):
    • print('>>> Invalid input!')
    • continue
    • else:
    • chosen_location = int(chosen_location) - 1 # adjust for array index to start at 0 not 1
    • return chosen_location
    • if __name__ == '__main__':
    • NoughtsAndCrosses().play()
Code
Diff
  • PLAYER_1 = 1
    PLAYER_2 = 2
    
    
    class NoughtsAndCrosses(object):
        """Basic implementation of Noughts and Crosses"""
        WIN_COMBOS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
        EMPTY_BOARD = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    
        def __init__(self):
            self.current_board = self.EMPTY_BOARD.copy()
            self.current_player = PLAYER_1  # game always starts with PLAYER_1
            self.player_names = {}
            self.location_lists = {
                PLAYER_1: [],
                PLAYER_2: []
            }
            self.player_markers = {
                PLAYER_1: "X",
                PLAYER_2: "O",
            }
        
        def _print_board(self):
            """Prints the current board"""
            print("--- Noughts and Crosses ---")
            print(f'{self.current_board[0]} : {self.current_board[1]} : {self.current_board[2]}')
            print("..........")
            print(f'{self.current_board[3]} : {self.current_board[4]} : {self.current_board[5]}')
            print("..........")
            print(f'{self.current_board[6]} : {self.current_board[7]} : {self.current_board[8]}')
        
        def play(self):
            self._print_welcome_message()
            self._get_player_names()
            while True:
                self._let_current_player_move()
                if self._player_has_won(self.current_player):
                    print(f"{self.player_names[self.current_player]}, you have won!")
                    break
                self._switch_current_player()
    
        def _let_current_player_move(self):
            print("Hi", self.player_names[self.current_player])
            while True:
                chosen_board_index = self._get_next_move()
                if self._location_is_taken(chosen_board_index):
                    print('>>> Position taken, try again!')
                    continue
                else:
                    self._update_board_and_location_lists(chosen_board_index)
                    self._print_board()
                    break
    
        def _update_board_and_location_lists(self, chosen_board_index):
            self.current_board[chosen_board_index] = self.player_markers[self.current_player]
            self.location_lists[self.current_player].append(chosen_board_index)
    
        @staticmethod
        def _print_welcome_message():
            print("*" * 50)
            print("Welcome to our Noughts and Crosses Game!")
            print("*" * 50)
    
        def _get_player_names(self):
            self.player_names[1] = input("Enter the name of the first player:\n> ")
            self.player_names[2] = input("Enter the name of the second player:\n> ")
    
        def _switch_current_player(self):
            if self.current_player == PLAYER_1:
                self.current_player = PLAYER_2
            else:
                self.current_player = PLAYER_1
    
        def _location_is_taken(self, board_index):
            return self.current_board[board_index] in self.player_markers.values()
    
        def _player_has_won(self, player):
            for win_combo in self.WIN_COMBOS:
                if set(win_combo) <= set(self.location_lists[player]):
                    return True
            return False  # if no winning combinations was found
    
        @staticmethod
        def _get_next_move():
            while True:
                chosen_location = input("Cross location(choose 1 - 9):\n> ")
                if not chosen_location.isdigit() or int(chosen_location) not in range(10):
                    print('>>> Invalid input!')
                    continue
                else:
                    chosen_location = int(chosen_location) - 1  # adjust for array index to start at 0 not 1
                    return chosen_location
    
    
    if __name__ == '__main__':
        NoughtsAndCrosses().play()
    
    • # constants
    • WIN_COMBOS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
    • BOARD = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    • def make_board():
    • """This function creates the board"""
    • print("--- Noughts and Crosses ---")
    • print(f'{BOARD[0]:<2}: {BOARD[1]:<2}: {BOARD[2]:>1}')
    • print("..........")
    • print(f'{BOARD[3]:<2}: {BOARD[4]:<2}: {BOARD[5]:>1}')
    • print("..........")
    • print(f'{BOARD[6]:<2}: {BOARD[7]:<2}: {BOARD[8]:>1}')
    • def main():
    • # Main menu
    • print("*" * 50)
    • print("Welcome to our Noughts and Crosses Game!")
    • print("*" * 50)
    • play_loc_list1 = []
    • play_loc_list2 = []
    • # Get player's names
    • player_1 = input("Enter the name of the first player:\n> ")
    • player_2 = input("Enter the name of the second player:\n> ")
    • while True:
    • turn = 1
    • # Player 1 turn
    • while turn == 1:
    • print("Hi", player_1)
    • while True:
    • make_board()
    • while True:
    • # User input validation loop:
    • loc_x = input("Cross location(choose 1 - 9):\n> ")
    • if not loc_x.isdigit() or int(loc_x) not in range(10):
    • print('>>> Invalid input!')
    • continue
    • else:
    • loc_x = int(loc_x)
    • break # break User input validation loop:
    • # Check if position is empty:
    • if BOARD[loc_x - 1] == 'X' or BOARD[loc_x - 1] == 'O':
    • print('>>> Position taken, try again!')
    • continue
    • else:
    • BOARD[loc_x - 1] = "X"
    • break # Break player 1 turn:
    • # Check win combos:
    • loc_attempt = loc_x - 1
    • play_loc_list1.append(loc_attempt)
    • play_loc_list1.sort()
    • for i in range(0, len(WIN_COMBOS)):
    • if WIN_COMBOS[i] == play_loc_list1:
    • print("You have won!")
    • break
    • make_board()
    • turn = 2
    • # Player 2 turn:
    • while turn == 2:
    • print("Hi", player_2)
    • while True:
    • make_board()
    • while True:
    • # User input validation loop:
    • loc_y = input("Noughts location(choose 1 - 9):\n> ")
    • if not loc_y.isdigit() or int(loc_y) not in range(10):
    • print('>>> Invalid input')
    • continue
    • else:
    • loc_y = int(loc_y)
    • break # break User input validation loop:
    • # Check if position is empty:
    • if BOARD[loc_y - 1] == 'X' or BOARD[loc_y - 1] == 'O':
    • print('>>> Position taken, try again!')
    • continue
    • else:
    • BOARD[loc_y - 1] = "O"
    • break # Break player 2 turn:
    • # Check win combos:
    • loc_attempt = loc_y - 1
    • play_loc_list2.append(loc_attempt)
    • play_loc_list2.sort()
    • for i in range(0, len(WIN_COMBOS)):
    • if WIN_COMBOS[i] == play_loc_list2:
    • print("You have won!")
    • break
    • PLAYER_1 = 1
    • PLAYER_2 = 2
    • make_board()
    • turn = 1
    • class NoughtsAndCrosses(object):
    • """Basic implementation of Noughts and Crosses"""
    • WIN_COMBOS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
    • EMPTY_BOARD = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    • def __init__(self):
    • self.current_board = self.EMPTY_BOARD.copy()
    • self.current_player = PLAYER_1 # game always starts with PLAYER_1
    • self.player_names = {}
    • self.location_lists = {
    • PLAYER_1: [],
    • PLAYER_2: []
    • }
    • self.player_markers = {
    • PLAYER_1: "X",
    • PLAYER_2: "O",
    • }
    • def _print_board(self):
    • """Prints the current board"""
    • print("--- Noughts and Crosses ---")
    • print(f'{self.current_board[0]} : {self.current_board[1]} : {self.current_board[2]}')
    • print("..........")
    • print(f'{self.current_board[3]} : {self.current_board[4]} : {self.current_board[5]}')
    • print("..........")
    • print(f'{self.current_board[6]} : {self.current_board[7]} : {self.current_board[8]}')
    • def play(self):
    • self._print_welcome_message()
    • self._get_player_names()
    • while True:
    • self._let_current_player_move()
    • if self._player_has_won(self.current_player):
    • print(f"{self.player_names[self.current_player]}, you have won!")
    • break
    • self._switch_current_player()
    • def _let_current_player_move(self):
    • print("Hi", self.player_names[self.current_player])
    • while True:
    • chosen_board_index = self._get_next_move()
    • if self._location_is_taken(chosen_board_index):
    • print('>>> Position taken, try again!')
    • continue
    • else:
    • self._update_board_and_location_lists(chosen_board_index)
    • self._print_board()
    • break
    • def _update_board_and_location_lists(self, chosen_board_index):
    • self.current_board[chosen_board_index] = self.player_markers[self.current_player]
    • self.location_lists[self.current_player].append(chosen_board_index)
    • @staticmethod
    • def _print_welcome_message():
    • print("*" * 50)
    • print("Welcome to our Noughts and Crosses Game!")
    • print("*" * 50)
    • def _get_player_names(self):
    • self.player_names[1] = input("Enter the name of the first player:\n> ")
    • self.player_names[2] = input("Enter the name of the second player:\n> ")
    • def _switch_current_player(self):
    • if self.current_player == PLAYER_1:
    • self.current_player = PLAYER_2
    • else:
    • self.current_player = PLAYER_1
    • def _location_is_taken(self, board_index):
    • return self.current_board[board_index] in self.player_markers.values()
    • def _player_has_won(self, player):
    • for win_combo in self.WIN_COMBOS:
    • if set(win_combo) <= set(self.location_lists[player]):
    • return True
    • return False # if no winning combinations was found
    • @staticmethod
    • def _get_next_move():
    • while True:
    • chosen_location = input("Cross location(choose 1 - 9):\n> ")
    • if not chosen_location.isdigit() or int(chosen_location) not in range(10):
    • print('>>> Invalid input!')
    • continue
    • else:
    • chosen_location = int(chosen_location) - 1 # adjust for array index to start at 0 not 1
    • return chosen_location
    • if __name__ == '__main__':
    • main()
    • NoughtsAndCrosses().play()