예제 #1
0
 def to_menu(self):
     """
     Function for to_menu_but
     """
     self.hide()
     self.game_start()
     self.main_ui.show()
     self.game = TicTacToe()
예제 #2
0
 def game_start(self):
     """
     help function, same actions for pve and pvp
     """
     self.start_res_but.hide()
     self.hint_but.show()
     self.enabled_all(True)
     self.game = TicTacToe()
     self.comp = Computer(load_dict_from_file("student_experience.txt"), self.game)
예제 #3
0
 def __init__(self):
     """
     1. An instance of the class is created for the game;
     2. Loading data for computer about previous games.
     """
     self.game = TicTacToe()
     self.player = Player(self.game)
     self.experience_path = "old_student_experience.txt"
     self.comp = Computer(load_dict_from_file(self.experience_path),
                          self.game)
     self.comp_turn = 0
예제 #4
0
    def prepare_next_move(self):
        """
        :return: ElemCourse class instance if on next move will be victory (else None) \
        and danger_elems: matrix that contains elements on which through the course will be a loss if you go to them
        """
        res_find_win_move = self.game.find_win_move()
        danger_elems = []
        for elem in self.game.negative():
            continue_game = TicTacToe(self.game.copy())
            continue_game.move(elem)
            if continue_game.find_win_move():
                danger_elems.append(elem)

        return res_find_win_move, danger_elems
예제 #5
0
 def __init__(self, teacher_dic, student_dic, start=None):
     """
     1. An instance of the class is created for the game;
     2. Loading data for computer about previous games.
     :param teacher_dic: teacher's experience
     :param student_dic: student's experience
     :param start: starting course of game
     """
     if start:
         self.game = start
     else:
         self.game = TicTacToe()
     self.teacher = Computer(teacher_dic, self.game)
     self.student = Computer(student_dic, self.game)
     self.student_turn = 1 if random(
     ) > 0.5 else 0  # if 1, student moves first, else teacher moves first
예제 #6
0
    def test_BoardMoveWinDiagonalLeft(self):
        #Arrange
        myBoardSize = 3
        difficulty = 2
        gameMode=1

        myTTT = TicTacToe(myBoardSize, gameMode, difficulty, True)
        myBoard = myTTT.board
        myBoard.makeMove("X",[0,2])
        myBoard.makeMove("X",[1,1])

        #Act        
        result = myTTT._getMoveCPU()        
        
        #Assert
        self.assertEqual(result,[2,0])
예제 #7
0
    def test_ParamDifficulty(self):
        #Arrange
        myBoardSize = 3
        difficulty = 3
        gameMode = 3

        #Act
        #Assert
        with(self.assertRaises(InvalidParameterException)):
            myTTT = TicTacToe(myBoardSize, gameMode, difficulty, True)
예제 #8
0
class LearningGame(object):
    """
    A game between student-computer and teacher-computer,
    where teacher-computer learns by LearningTeacher,
    and student-computer learns by LearningStudent.
    """
    def __init__(self, teacher_dic, student_dic, start=None):
        """
        1. An instance of the class is created for the game;
        2. Loading data for computer about previous games.
        :param teacher_dic: teacher's experience
        :param student_dic: student's experience
        :param start: starting course of game
        """
        if start:
            self.game = start
        else:
            self.game = TicTacToe()
        self.teacher = Computer(teacher_dic, self.game)
        self.student = Computer(student_dic, self.game)
        self.student_turn = 1 if random(
        ) > 0.5 else 0  # if 1, student moves first, else teacher moves first

    def start(self, probability_random_move):
        """
        :param probability_random_move: chance of random move
        :return: course of game
        """
        while True:
            self.teacher.move(probability_random_move) if self.student_turn == 0 \
                else self.student.move(probability_random_move)
            if self.game.winner() == self.game.last_turn:
                break
            if len(self.game) == 9:  # field is filling
                break
        if self.student_turn == self.game.winner():
            status = 1
        elif self.student_turn == 1 - self.game.winner():
            status = -1
        else:
            status = 0
        return self.game, status
예제 #9
0
    def test_BoardMoveCPUEasy(self):
        #Arrange
        myBoardSize = 3
        difficulty = 1
        gameMode = 1

        myTTT = TicTacToe(myBoardSize, gameMode, difficulty, True)
        myBoard = myTTT.board
        myBoard.makeMove("X",[0,2])
        myBoard.makeMove("X",[1,1])
        
        #Act        
        result = myTTT._getMoveCPU()
        
        while(result == [2,0]):
            myBoard.GameBoard[2][0] = '_'
            result = myTTT._getMoveCPU()            
        
        #Assert
        self.assertNotEqual(result,[2,0])
예제 #10
0
파일: PvPGame.py 프로젝트: Xapulc/TicTacToe
class GamePvP(object):
    """
    Game player vs player
    """
    def __init__(self):
        self.game = TicTacToe()
        self.playerOne = Player(self.game)
        self.playerTwo = Player(self.game)

    def start(self):
        print("Welcome to TicTacToe, v. 2.7218281828459045")
        while True:
            while True:
                print("First player move")
                self.playerOne.move()
                print(self.game)
                if self.game.winner() == 1:
                    print("First player win!!!")
                    print("Congratulations!!!")
                    break
                elif len(self.game) == 9:
                    print("Nobody wins")
                    break
                print("Second player move")
                self.playerTwo.move()
                print(self.game)
                if self.game.winner() == 0:
                    print("Second player win!!!")
                    print("Congratulations!!!")
                    break
            agreement = input(
                "Do you want to play new game: 1 - yes, other - no")
            if agreement == '1':
                print("Preparing...")
                self.__init__()
                continue
            else:
                break
예제 #11
0
def learn_student(count, probability_random_move):
    """
    :param count: number of games to be played by student with teacher (will be played 72 * count games)
    :param probability_random_move: this is parameter of random move
    This is script code for teaching student experience-based teacher
    """
    student_wins = 0
    teacher_wins = 0
    student_experience_path = "student_experience.txt"
    teacher_experience_path = "old_student_experience.txt"
    student_dic = load_dict_from_file(student_experience_path)
    teacher_dic = load_dict_from_file(teacher_experience_path)
    for i in range(3):
        for j in range(3):
            for k in range(3):
                for l in range(3):
                    if not (l == j and k == i):
                        filtered_teacher_dic = teacher_dic.copy()
                        filtered_student_dic = student_dic.copy()
                        beginning_game = TicTacToe(
                            [ElemCourse(i, j),
                             ElemCourse(k, l)])
                        filter_data(beginning_game, filtered_teacher_dic)
                        filter_data(beginning_game, filtered_student_dic)
                        for _ in range(count):
                            game, res, is_student_win = create_learning_student_game(
                                filtered_teacher_dic, filtered_student_dic,
                                probability_random_move, beginning_game)
                            student_wins += (1 if is_student_win == 1 else 0)
                            teacher_wins += (1 if is_student_win == -1 else 0)
                            student_dic[tuple(game)] = res
                        print(
                            f"complete on {100 * (27 * i + 9 * j + 3 * k + l) / 81:.0f}%"
                        )

    print(f"Student has {100 * (student_wins / (72 * count)):.2f}% wins")
    print(f"Teacher has {100 * (teacher_wins / (72 * count)):.2f}% wins")
    save_dict_to_file(student_dic, student_experience_path)
    print(len(student_dic.keys()))
예제 #12
0
파일: PvPGame.py 프로젝트: Xapulc/TicTacToe
 def __init__(self):
     self.game = TicTacToe()
     self.playerOne = Player(self.game)
     self.playerTwo = Player(self.game)
예제 #13
0
class GameWindow(QWidget):
    """
    Class is responsible for window with game
    Contains playing field, start/reset, to main menu, hint and radio buttons
    """

    def __init__(self):
        QWidget.__init__(self)
        uic.loadUi("game/game.ui", self)
        self.radio_buts = [self.pl_first, self.comp_first]
        self.buttons = [self.but_1, self.but_2, self.but_3,
                        self.but_4, self.but_5, self.but_6,
                        self.but_7, self.but_8, self.but_9]
        self.ico = "game/ttt.svg"
        self.but_ico = "game/but_ico.svg"
        self.game = None
        self.pvp_window_prepare = self.game_window_prepare("pvp")
        self.pve_window_prepare = self.game_window_prepare("pve")
        self.comp_turn = None
        self.comp = None
        self.last_hint_num = None
        self.experience_path = "old_student_experience.txt"
        self.initUI()

    def initUI(self):
        """
        Initialisation GUI and connecting buttons with functions
        """
        for but in self.radio_buts:
            but.hide()
        for key, but in enumerate(self.buttons):
            but.clicked.connect(self.player_move(key))
        self.enabled_all(False)
        self.setWindowIcon(QIcon(self.ico))
        self.to_menu_but.clicked.connect(self.to_menu)
        self.hint_but.clicked.connect(self.hint)
        self.hint_but.setIcon(QIcon(self.but_ico))
        self.hint_but.setIconSize(QSize(40, 40))

    def hint(self):
        """
        Computer calculates more effective move and set in cell "!"
        """
        el = self.comp.hint_move()
        self.last_hint_num = 3 * el.x + el.y
        self.buttons[self.last_hint_num].setText("!")

    def to_menu(self):
        """
        Function for to_menu_but
        """
        self.hide()
        self.game_start()
        self.main_ui.show()
        self.game = TicTacToe()

    def set_main_ui(self, main_ui):
        """
        This need for connection with game UI and main menu UI
        :param main_ui: MainWindow class instance
        """
        self.main_ui = main_ui

    def comp_move(self):
        """
        Make computer move in this game and checking end
        """
        self.comp.move()
        last_move = self.game[len(self.game) - 1]
        self.buttons[3*last_move.x + last_move.y].setText("o" if self.game.current_turn else "x")
        if self.game.check_end():
            self.end_game()
        else:
            self.status_label.setText("Player's move")

    def player_move(self, key):
        """
        :param key: number of button
        :return: an function which, at the press of a button, set in cell O or X
        """
        def helper():
            try:
                self.game.add(ElemCourse(key // 3, key % 3))
            except AssertionError:
                pass
            else:
                if self.last_hint_num is not None:
                    self.buttons[self.last_hint_num].setText("")
                    self.last_hint_num = None
                self.buttons[key].setText("o" if self.game.current_turn else "x")
                if self.game.check_end():
                    self.end_game()
                else:
                    if self.comp_turn is not None:
                        self.status_label.setText(f"Computer's move")
                        self.comp_move()
                    else:
                        self.status_label.setText(f"{'First' if self.game.current_turn else 'Second'} player's move")

        return helper

    def end_game(self):
        """
        Final actions at the end of the game
        """
        self.enabled_all(False)
        self.start_res_but.setText("Reset")
        self.start_res_but.show()
        self.hint_but.hide()
        if self.comp_turn is None:
            self.start_res_but.clicked.disconnect(self.pvp_start)
            self.start_res_but.clicked.connect(self.pvp_window_prepare)
        else:
            self.start_res_but.clicked.disconnect(self.pve_start)
            self.start_res_but.clicked.connect(self.pve_window_prepare)

        if self.game.winner() == -1:
            self.status_label.setText("Nobody wins")
        else:
            if self.comp_turn is None:
                self.status_label.setText(f"{'Second' if self.game.current_turn else 'First'} player wins!")
            else:
                self.status_label.setText(f"{'Computer' if self.comp_turn == self.game.winner() else 'Player'} wins!")

        if self.comp_turn is not None:
            data = load_dict_from_file(self.experience_path)
            data[tuple(self.game)] = self.game.winner()
            save_dict_to_file(data, self.experience_path)

    def enabled_all(self, flag):
        """
        makes all buttons responsible for the game [un]available for pressing
        :param flag: True (enabled) or False (disabled)
        """
        for but in self.buttons:
            but.setEnabled(flag)

    def game_window_prepare(self, mode):
        """
        :param mode: pvp or pve
        :return: an function which, at the press of a button, prepare game for pve or pvp
        """
        def helper():
            for but in self.buttons:
                but.setText("")
                but.show()

            for but in self.radio_buts:
                but.show() if mode == "pve" else but.hide()
            self.radio_buts[0].setChecked(True)

            self.enabled_all(False)
            self.status_label.setText("")

            self.start_res_but.setText("Start")
            try:
                self.start_res_but.clicked.disconnect(self.pvp_window_prepare)
            except TypeError:
                pass
            try:
                self.start_res_but.clicked.disconnect(self.pve_window_prepare)
            except TypeError:
                pass
            self.start_res_but.clicked.connect(self.pve_start if mode == "pve" else self.pvp_start)
            self.start_res_but.show()
            self.hint_but.hide()

            self.comp_turn = None
            self.show()

        return helper

    def game_start(self):
        """
        help function, same actions for pve and pvp
        """
        self.start_res_but.hide()
        self.hint_but.show()
        self.enabled_all(True)
        self.game = TicTacToe()
        self.comp = Computer(load_dict_from_file("student_experience.txt"), self.game)

    def pvp_start(self):
        """
        function for start button in pvp game
        """
        self.game_start()
        self.comp_turn = None
        self.status_label.setText("First player's move")

    def pve_start(self):
        """
        function for start button in pve game
        """
        self.game_start()
        self.comp_turn = 0 if self.radio_buts[0].isChecked() else 1
        for but in self.radio_buts:
            but.hide()

        if self.comp_turn == 1:
            self.status_label.setText("Computer's move")
            self.comp_move()
        else:
            self.status_label.setText("Player's move")
예제 #14
0
class PlayerGame(object):
    """
    A game with player,
    call beginning_game() to begin game with player
    """
    def __init__(self):
        """
        1. An instance of the class is created for the game;
        2. Loading data for computer about previous games.
        """
        self.game = TicTacToe()
        self.player = Player(self.game)
        self.experience_path = "old_student_experience.txt"
        self.comp = Computer(load_dict_from_file(self.experience_path),
                             self.game)
        self.comp_turn = 0

    def start(self):
        """
        Start a game with computer
        Main control thread of game
        """
        print("Welcome to TicTacToe, v. 2.7218281828459045")
        while True:
            while True:
                try:
                    who_first = input("Who first: 0 - player, 1 - computer?")
                    assert who_first in ('0', '1')
                except AssertionError:
                    print("Please, write 0 or 1")
                else:
                    break

            self.comp_turn = int(who_first)
            while True:
                self.player.move() if self.comp_turn == 0 else self.comp.move()
                print(self.game)
                if self.game.winner() == 1:
                    print("You win!!!") if self.comp_turn == 0 else print(
                        "You lose")
                    print("Congratulations!!!")
                    break
                elif len(self.game) == 9:
                    print("Nobody wins")
                    break

                self.comp.move() if self.comp_turn == 0 else self.player.move()
                print(self.game)
                if self.game.winner() == 0:
                    print("You lose") if self.comp_turn == 0 else print(
                        "You win!!!")
                    print("Congratulations!!!")
                    break

            data = load_dict_from_file(self.experience_path)
            data[tuple(self.game)] = self.game.winner()
            save_dict_to_file(data, self.experience_path)

            agreement = input(
                "Do you want to play new game: 1 - yes, other - no")
            if agreement == '1':
                print("Preparing...")
                self.__init__()
                continue
            else:
                break