Пример #1
0
 def test_illegal_move(self):
     try:
         game = Nim(10, 5, 1)
         game.move(6)
     except AssertionError:
         # Exception caught, passed test
         self.assertTrue(True)
Пример #2
0
    def __init__(self, inputUI, parent=None):
        super(GUIWindow, self).__init__(parent)
        self.m_ui = inputUI
        self.m_ui.setupUi(self)
        self.m_Nim = Nim()

        ## Actions to functions linkage
        self.m_ui.playButton.clicked.connect(self.startGame)
        self.m_ui.resetButton.clicked.connect(self.resetGame)
Пример #3
0
 def test_full_game(self):
     game = Nim(10, 3, 1)
     game.move(1)
     game.move(3)
     game.move(2)
     game.move(3)
     game.move(1)
     self.assertTrue(game.is_terminal_state())
Пример #4
0
 def initialize_game(self, cfg, verbose):
     game_type = cfg["game"]["type"]
     if game_type == "nim":
         game = Nim(cfg, verbose)
     else:
         game = OldGold(cfg, verbose)
     return game
Пример #5
0
    def play_game(i):
        """
        Plays out one isolated game
        """

        print("Game", i)

        game = Nim(N, K, starting_player=P)
        mcts = RolloutMCTS(game, UCT(), RandomPolicy())

        game_state = game.initial_state()

        if verbose:
            to = game.describe_state_transition(game_state)

        tree = None

        while game.winner(game_state) is Winner.NA:
            # Tree search move for player 1
            tree, game_state = mcts.search(game_state, M, root=tree)

            if verbose:
                print(to(game_state))
                to = game.describe_state_transition(game_state)

            # # Random move for player 2
            # p2_moves = game.child_states(game_state)
            # if p2_moves:
            #     tree, game_state = choice(list(zip(tree.children, p2_moves)))

            # if verbose:
            #     print(to(game_state))
            #     to = game.describe_state_transition(game_state)

        return 1 if game.winner(game_state) is W else 0
Пример #6
0
def main():
    n, k, num_games, verbose, starting_player, max_rollouts = setup_game()

    results = []
    game_num = 1
    while num_games >= game_num:
        if verbose:
            print("Spill nr. {}\n".format(game_num))
        nim = Nim(n, k, starting_player)
        while nim.get_moves():
            if nim.get_next_player() == 1:
                mc = MonteCarlo(nim, max_rollouts)
                move = mc.run()
            else:
                mc = MonteCarlo(nim, max_rollouts)
                move = mc.run()
            nim.do_move(move)
            if verbose == 1:
                display_move(nim.player, move, nim.state)

        if nim.get_result(nim.player) == 1:
            results.append(nim.player)
        game_num += 1
        if verbose:
            display_winning_player(nim.player)
            print("\n=======================================\n")

    display_results(results)
Пример #7
0
    def test_initialize(self):
        N = 50
        K = 7
        P = 1
        game = Nim(N, K, P)

        self.assertEqual(game.get_initial_state(), N)
        self.assertEqual(game.get_state(), N)
        self.assertEqual(game.get_max_removable(), K)
        self.assertEqual(game.get_active_player(), P)
Пример #8
0
def start_game():
    play = input("Welcome to nim, would you like to play? (y/n)")

    while play.lower() == 'y':
        print("Lets play!")

        game = Nim()
        game.start()
        game.tell_winner()

        play = input("Would you like to play again? (y/n)")

    print("Thanks for playing!")
Пример #9
0
def newgame():
    global n, rects, coords, locked
    n = Nim(ncols)
    c.delete("all")
    c.config(width=(ncols) * 100)
    numselector.grid(row=2)
    rects = [[] for i in range(ncols)]
    coords = [[] for i in range(ncols)]
    for i in range(ncols):
        for j in range(n.piles[i]):
            topy = 400 - (j + 1) * 15
            coords[i].append(topy)
            r = c.create_rectangle(i * 100 + 20,
                                   topy,
                                   i * 100 + 80,
                                   topy + 15,
                                   fill="green")
            rects[i].append(r)
    locked = False
Пример #10
0
 def create_game(self):
     if self.type == "nim":
         game = Nim(self.N, self.K, self.P, self.verbose)
     else:
         game = Ledge(self.B, self.P, self.verbose)
     return game
Пример #11
0
 def test_nim_player_move(self):
     nim = Nim(9)
     nim.player_move(2)
     self.assertEqual(nim.player_move(2), 2)
Пример #12
0
 def test_nim_number_too_big_edge(self):
     nim = Nim(2)
     nim.player_move(3)
     output = sys.stdout.getvalue().strip().strip("\n")
     self.assertEqual(output, 'Es sind keine 3 Hölzer mehr übrig, bitte nimm weniger!')
Пример #13
0
from nim import Nim
from random import randrange

nim = Nim(randrange(9,15,2))
nim.execute()
Пример #14
0
 def test_random_initial_player(self):
     game = Nim(10, 5, 3)
     self.assertIn(game.get_active_player(), [1, 2])
Пример #15
0
 def test_legal_move(self):
     game = Nim(10, 5, 1)
     game.move(2)
     self.assertEqual(game.get_state(), 8)
     self.assertFalse(game.is_terminal_state())
     self.assertEqual(game.get_active_player(), 2)
Пример #16
0
 def test_nim_computer_move_three(self):
     nim = Nim(9)
     nim.computer_move(3)
     output = sys.stdout.getvalue().strip().strip("\n")
     self.assertEqual(output, 'Der Computer nimmt 1 Hölzer.')
Пример #17
0
class GUIWindow(QtWidgets.QMainWindow):
    ## constructor
    def __init__(self, inputUI, parent=None):
        super(GUIWindow, self).__init__(parent)
        self.m_ui = inputUI
        self.m_ui.setupUi(self)
        self.m_Nim = Nim()

        ## Actions to functions linkage
        self.m_ui.playButton.clicked.connect(self.startGame)
        self.m_ui.resetButton.clicked.connect(self.resetGame)

    ## Helper functions

    # @brief starts the game
    # @details Randomly generates three piles and asks the user if they want to go
    # first or to let the computer go first.
    def startGame(self):
        if self.m_ui.playButton.text() == 'PLAY':
            self.m_Nim.generate_piles()
            self.m_ui.leftStack.setText(str(self.m_Nim.piles[0]))
            self.m_ui.middleStack.setText(str(self.m_Nim.piles[1]))
            self.m_ui.rightStack.setText(str(self.m_Nim.piles[2]))

            # asks user if they want to go first
            self.getFirstPlayer()

            # disable play button and enable reset button
            #self.m_ui.playButton.setEnabled(False)
            self.m_ui.playButton.setText("Enter")
            self.m_ui.resetButton.setEnabled(True)
            # disconnect startGame function to playButton
            self.m_ui.playButton.disconnect()
            # connect updatePiles function to playButton
            self.m_ui.playButton.clicked.connect(self.updatePiles)

            # start thread to play game
            #gameWorker = PlayGameThread(self)
            #gameWorker.start()

    # @brief asks user if they want to make the first move
    # @details Opens a message window and asks the user if they want to make the
    # first move.
    def getFirstPlayer(self):
        # create a message window asking if user wants to make the first move
        firstMsgBox = QMessageBox(QMessageBox.Question, "First Player",
                                  "Would you like to go first?")
        firstMsgBox.addButton(QMessageBox.Yes)
        firstMsgBox.addButton(QMessageBox.No)
        firstMsgBox.setDefaultButton(QMessageBox.No)

        # save the user's reply to message box
        reply = firstMsgBox.exec()
        if reply == QMessageBox.Yes:
            print('You are making the first move...')
            self.NextPlayer = 0  # user
        elif reply == QMessageBox.No:
            print('The computer is making the first move...')
            self.NextPlayer = 1  # computer
            time.sleep(1)
        else:
            print('Invalid selection')
            sys.exit()

    # @brief updates the piles and displays with players' moves
    # @details The next player's move updates the piles and the stack displays
    # are updated accordingly.
    def updatePiles(self):
        # check that button says 'Enter'
        if self.m_ui.playButton.text() == 'Enter':
            # check which player is next and apply their move
            #if self.NextPlayer == 0:
            # Get the user's move
            pile, n_rem = self.checkUserInput()
            # check that the user has given a valid move
            if (pile != None) and (n_rem != None):
                self.m_Nim.user_moves(pile, n_rem)
                self.NextPlayer = 1
                #time.sleep(1)

            # check if game is over
            if self.m_Nim.game_over():
                self.printEndMessage()

            if self.NextPlayer == 1:
                # update piles with the computer's move
                self.m_Nim.cp_moves()
                self.NextPlayer = 0
                print("Now it's your turn to make a move...")
                #time.sleep(1)

            # check if game is over
            if self.m_Nim.game_over():
                self.printEndMessage()

        # update stack displays
        self.m_ui.leftStack.setText(str(self.m_Nim.piles[0]))
        self.m_ui.middleStack.setText(str(self.m_Nim.piles[1]))
        self.m_ui.rightStack.setText(str(self.m_Nim.piles[2]))

    # @brief Checks pile inputs for the user's move
    # @details Checks the inputs for each pile to determine what pile the user has
    # selected to remove from and the amount the want to take away.
    def checkUserInput(self):
        #if self.m_ui.playButton.text() == 'Enter':
        stackInputs = [
            self.m_ui.userInput.itemAt(i).widget()
            for i in range(self.m_ui.userInput.count())
        ]
        count = 0
        pile = 0
        n_rem = 0
        for i in range(len(stackInputs)):  # check that input is not empty
            if stackInputs[i].text():
                count += 1  # keeps track of how many piles had input
                pile = i  # save the pile user entered input for
                n_rem = int(stackInputs[i].text())
            # clear the QLineEdit widgets
            stackInputs[i].clear()

        # check that the user's input are valid moves
        if count > 1 or count < 1:
            print('You can only remove rocks from one pile, Try again')
            pile = None
            n_rem = None
        elif pile not in range(3):
            print('Not a valid pile choice, Try again')
            pile = None
            n_rem = None
        elif self.m_Nim.piles[pile] <= 0:
            print('That pile is empty, Choose another pile')
            pile = None
            n_rem = None
        elif (n_rem <= 0) or (n_rem > self.m_Nim.piles[pile]):
            print('Not a valid amount to remove, Try again')
            pile = None
            n_rem = None

        return pile, n_rem

    def playGame(self):
        # chcek piles and see if game is over
        while self.m_Nim.game_over():
            # update piles with players' moves
            self.updatePiles()
            QtGui.qApp.processEvents()
            time.sleep(1)

        # game is over; print closing messages
        self.printEndMessage()

    # @brief prints a message when the game is over
    # @details Prints a game over banner to the terminal window and presetns a message
    # based on whether the user wins or loses.
    def printEndMessage(self):
        self.m_Nim.print_game_over()
        if self.NextPlayer == 0:
            print("Congratulations!! You have won...Tell me how you did it")
        else:
            print("Sorry, but you LOST! You should keep trying.")

        # reset the game
        self.resetGame()

    # @brief resets the pile displays
    # @details This function resets the piles to 0 and updates the stack displays.
    def resetGame(self):
        print('The game has been reset...')
        # reset the stacks to 0
        self.m_ui.leftStack.setText(str(0))
        self.m_ui.middleStack.setText(str(0))
        self.m_ui.rightStack.setText(str(0))

        # enable play button and disable reset button
        #self.m_ui.playButton.setEnabled(True)
        self.m_ui.playButton.setText("PLAY")
        self.m_ui.resetButton.setEnabled(False)
        # disconnect updatePiles function from playButton
        self.m_ui.playButton.disconnect()
        # connect startGame function to playButton
        self.m_ui.playButton.clicked.connect(self.startGame)
Пример #18
0
 def test_nim_number_too_small(self):
     nim = Nim(9)
     nim.player_move(-1)
     output = sys.stdout.getvalue().strip().strip("\n")
     self.assertEqual(output, 'Du musst zwischen 1 und 3 Hölzer nehmen!')
Пример #19
0
from nim import Nim
from random import randrange

nim = Nim(randrange(9, 15, 2))
nim.execute()
Пример #20
0
 def test_terminal_move(self):
     game = Nim(10, 9, 1)
     game.move(9)
     game.move(1)
     self.assertTrue(game.is_terminal_state())
     self.assertEqual(game.get_active_player(), 2)
Пример #21
0
from tkinter import *
import random
from nim import Nim
ncols = 3
n = Nim(ncols)
F = Frame()
stv = StringVar(F)
stv.set("3")

d = [str(i) for i in range(1, 11)]
numselector = OptionMenu(F, stv, *d)
c = Canvas(F, width=(ncols) * 100, height=400)
F.pack()
c.grid()


def changepiles(*args):
    global ncols
    ncols = int(stv.get())
    if not locked:
        newgame()


stv.trace_add('write', changepiles)


def newgame():
    global n, rects, coords, locked
    n = Nim(ncols)
    c.delete("all")
    c.config(width=(ncols) * 100)
Пример #22
0
 def test_get_legal_moves(self):
     game = Nim(7, 5, 1)
     self.assertEqual(game.get_legal_moves(), [1, 2, 3, 4, 5])
     game.move(5)
     self.assertEqual(game.get_legal_moves(), [1, 2])
Пример #23
0
def main():
    www = False
    quiz = False
    gallows_flag = False
    bulls_cows = False
    nim_flag = False

    for event in longpoll.listen():

        if event.type == VkBotEventType.MESSAGE_NEW:
            request = event.obj.message['text'].lower()
            if www:
                if request == 'ответ':
                    write_message(event.obj.message['from_id'], answer,
                                  keyboard_question)
                    if comm:
                        write_message(event.obj.message['from_id'], comm,
                                      keyboard_question)
                    quest, answer, comm = what_where_when()
                    write_message(event.obj.message['from_id'], quest,
                                  keyboard_question)
                elif request == 'дальше':
                    quest, answer, comm = what_where_when()
                    write_message(event.obj.message['from_id'], quest,
                                  keyboard_question)
                elif request == 'стоп':
                    write_message(event.obj.message['from_id'], "Что дальше?")
                    www = False
                else:
                    if request == answer.lower():
                        write_message(event.obj.message['from_id'],
                                      'Правильный ответ!', keyboard_question)
                        quest, answer, comm = what_where_when()
                        write_message(event.obj.message['from_id'], quest,
                                      keyboard_question)
                    else:
                        write_message(
                            event.obj.message['from_id'],
                            'Что-то не то.\nНапишите "СТОП", чтобы закончить.',
                            keyboard_question)
            elif quiz:
                if request == 'ответ':
                    write_message(event.obj.message['from_id'],
                                  COUNTRIES[answer_cnt_id], keyboard_question)
                elif request == 'дальше':
                    pass
                elif request == 'стоп':
                    write_message(event.obj.message['from_id'], "Что дальше?")
                    quiz = False
                    continue
                else:
                    if request == COUNTRIES[answer_cnt_id].lower(
                    ) or request == str(variants.index(answer_cnt_id) + 1):
                        write_message(event.obj.message['from_id'],
                                      'Правильный ответ!', keyboard_question)
                        correct_answers += 1
                    else:
                        write_message(
                            event.obj.message['from_id'],
                            'Неправильный ответ\nОтвет: ' +
                            COUNTRIES[answer_cnt_id], keyboard_question)
                if counter < 10:
                    count_list.remove(COUNTRIES[answer_cnt_id])
                    answer_cnt_id, variants, attachment = country_quiz(
                        count_list)
                    write_message(event.obj.message['from_id'], quest_flag,
                                  keyboard_question, attachment)
                    write_message(event.obj.message['from_id'],
                                  variants_to_line(variants),
                                  keyboard_question)
                    counter += 1
                else:
                    quiz = False
                    ln = "Результаты викторины: " + str(
                        correct_answers) + "/10"
                    write_message(event.obj.message['from_id'],
                                  ln + '\nЧто дальше?')
            elif gallows_flag:
                if request == 'стоп':
                    write_message(event.obj.message['from_id'], "Что дальше?")
                    gallows_flag = False
                    continue
                elif request == '<' or request == '>':
                    kb_num = next_keyboard(kb_num, request, event)
                else:
                    result, word_list = gallows(word_gallows, request,
                                                word_list)
                    if result:
                        write_message(event.obj.message['from_id'],
                                      "Эта буква есть в слове!",
                                      keyboard_gallows1)
                        line = 'Тема: ' + theme + '\nСлово: ' + ' '.join(
                            word_list) + '\nЖизней: ' + '<3 ' * lives
                        write_message(event.obj.message['from_id'], line,
                                      keyboard_gallows1)
                        kb_num = 1
                    else:
                        write_message(event.obj.message['from_id'],
                                      "Буквы нет в слове!", keyboard_gallows1)
                        lives -= 1
                        line = 'Тема: ' + theme + '\nСлово: ' + ' '.join(
                            word_list) + '\nЖизней: ' + '<3 ' * lives
                        write_message(event.obj.message['from_id'], line,
                                      keyboard_gallows1)
                        kb_num = 1
                    if '_' not in word_list:
                        write_message(event.obj.message['from_id'],
                                      "Вы победили!")
                        gallows_flag = False
                    if lives == 0:
                        write_message(event.obj.message['from_id'],
                                      "Вы проиграли!")
                        gallows_flag = False
            elif bulls_cows:
                if request == 'стоп':
                    write_message(event.obj.message['from_id'], "Что дальше?")
                    bulls_cows = False
                    continue
                elif request == 'новая игра':
                    moves = 0
                    nm_cows_bulls = NUMBERS[:]
                    random.shuffle(nm_cows_bulls)
                    nm_cows_bulls = nm_cows_bulls[:4]
                    write_message(event.obj.message['from_id'],
                                  "Найди число, задуманное шлёпой",
                                  keyboard_bulls_cows)
                else:
                    if request.isdigit() and len(
                            request) == 4 and repeat_letter(request):
                        pass
                    elif request.isdigit() is False or len(request) != 4:
                        write_message(event.obj.message['from_id'],
                                      'Ход - четырехзначное число',
                                      keyboard_bulls_cows)
                        continue
                    elif repeat_letter(request) is False:
                        write_message(event.obj.message['from_id'],
                                      'Цифры не должны повторяться',
                                      keyboard_bulls_cows)
                        continue
                    line, win = bulls_and_cows(list(request), nm_cows_bulls)
                    write_message(event.obj.message['from_id'], line,
                                  keyboard_bulls_cows)
                    moves += 1
                    if win:
                        write_message(event.obj.message['from_id'],
                                      'Мууу! Победа!\nХодов: ' + str(moves))
                        bulls_cows = False
            elif nim_flag:
                if request == 'стоп':
                    write_message(event.obj.message['from_id'], "Что дальше?")
                    nim_flag = False
                    continue
                elif num_stones:
                    if request == '1' or request == '2' or request == '3':
                        nm_stones = request
                        write_message(event.obj.message['from_id'],
                                      'Введите кол-во забираемых камней',
                                      keyboard_nim)
                        num_stones = False
                    else:
                        write_message(event.obj.message['from_id'],
                                      'Введите номер кучи', keyboard_nim)
                else:
                    play_mv = request
                    if play_mv.isdigit() is False:
                        write_message(event.obj.message['from_id'],
                                      'Введите кол-во забираемых камней',
                                      keyboard_nim)
                        continue
                    if ((nm_stones == '1'
                         and int(play_mv) <= nim_play.get_stones1()) or
                        (nm_stones == '2'
                         and int(play_mv) <= nim_play.get_stones2()) or
                        (nm_stones == '3' and int(play_mv) <=
                         nim_play.get_stones3())) and int(play_mv) > 0:
                        pass
                    else:
                        write_message(event.obj.message['from_id'],
                                      'Введите кол-во забираемых камней',
                                      keyboard_nim)
                        continue
                    end, ln1, ln2 = nim_play.play(int(nm_stones), int(play_mv))
                    write_message(event.obj.message['from_id'], ln1,
                                  keyboard_nim)
                    write_message(event.obj.message['from_id'], ln2,
                                  keyboard_nim)
                    if end:
                        write_message(event.obj.message['from_id'],
                                      'ЧЕЛОВЕК ПОБЕДИЛ!')
                        nim_flag = False
                        continue
                    end, ln1, ln2 = nim_play.play()
                    write_message(event.obj.message['from_id'], ln1,
                                  keyboard_nim)
                    write_message(event.obj.message['from_id'], ln2,
                                  keyboard_nim)
                    if end:
                        write_message(event.obj.message['from_id'],
                                      'ШЛЁПА ПОБЕДИЛ!')
                        nim_flag = False
                        continue
                    num_stones = True
                    write_message(event.obj.message['from_id'],
                                  'Введите номер кучи', keyboard_nim)
            else:
                if request == 'привет':
                    write_message(event.obj.message['from_id'], "Привет!")
                elif request == 'пока':
                    write_message(event.obj.message['from_id'], "До встречи")
                elif request == 'анекдоты':
                    write_message(event.obj.message['from_id'], get_joke())
                elif request == 'случайная картинка':
                    write_message(event.obj.message['from_id'], "Держи",
                                  keyboard_main, random_pic())
                elif request == 'ним':
                    st1, st2, st3 = randint(5,
                                            20), randint(5,
                                                         20), randint(5, 20)
                    nim_play = Nim(st1, st2, st3)
                    ln = 'Кол-во камней в первой куче: ' + str(st1) + '\nКол-во камней во второй куче: ' + str(st2) \
                         + '\nКол-во камней в третьей куче: ' + str(st3)
                    write_message(event.obj.message['from_id'], ln,
                                  keyboard_nim)
                    end, ln1, ln2 = nim_play.play()
                    write_message(event.obj.message['from_id'], ln1,
                                  keyboard_nim)
                    write_message(event.obj.message['from_id'], ln2,
                                  keyboard_nim)
                    nim_flag, num_stones = True, True
                    write_message(event.obj.message['from_id'],
                                  'Введите номер кучи', keyboard_nim)
                    nm_stones, play_mv = 0, 0
                elif request == 'быки и коровы':
                    moves = 0
                    nm_cows_bulls = NUMBERS[:]
                    random.shuffle(nm_cows_bulls)
                    nm_cows_bulls = nm_cows_bulls[:4]
                    write_message(event.obj.message['from_id'],
                                  "Найди число, задуманное шлёпой",
                                  keyboard_bulls_cows)
                    bulls_cows = True
                elif request == 'виселица':
                    theme, word_gallows = random_word()
                    word_list = ['_'] * len(word_gallows)
                    lives = 10
                    line = 'Тема: ' + theme + '\nСлово: ' + ' '.join(
                        word_list) + '\nЖизней: ' + '<3 ' * lives
                    kb_num = 1
                    write_message(event.obj.message['from_id'], line,
                                  keyboard_gallows1)
                    gallows_flag = True
                elif request == 'что? где? когда?' or request == 'чгк':
                    www = True
                    quest, answer, comm = what_where_when()
                    write_message(event.obj.message['from_id'], quest,
                                  keyboard_question)
                elif request == 'викторина по флагам':
                    quiz = True
                    count_list = COUNTRIES[:]
                    counter, correct_answers = 1, 0
                    answer_cnt_id, variants, attachment = country_quiz(
                        count_list)
                    write_message(event.obj.message['from_id'], quest_text,
                                  keyboard_question)
                    write_message(event.obj.message['from_id'], quest_flag,
                                  keyboard_question, attachment)
                    write_message(event.obj.message['from_id'],
                                  variants_to_line(variants),
                                  keyboard_question)
                else:
                    write_message(event.obj.message['from_id'],
                                  "Сложно! Я же просто кот")
Пример #24
0
 def test_nim_no_number(self):
     nim = Nim(9)
     nim.player_move('STRING')
     output = sys.stdout.getvalue().strip().strip("\n")
     self.assertEqual(output, 'Du musst eine Zahl eingeben!')