示例#1
0
 def testfinished(self):
     t1 = Guess('a')
     self.assertEqual(t1.secretWord, 'a')
     t2 = Guess('toomuchhomework')
     self.assertEqual(t2.secretWord, 'toomuchhomework')
     t3 = Guess('chicken')
     self.assertEqual(t3.secretWord, 'chicken')
     print('finished test ended')
示例#2
0
    def test_collision(self):
        sample_clue = Clue(0, 2, 4, "D", "", 0, "KIND")
        sample_clue_2 = Clue(0, 3, 5, "D", "", 1, "SPACE")
        sample_clue_3 = Clue(2, 0, 4, "A", "", 2, "IDEA")

        sample_guess = Guess(sample_clue, "KIND", 4)
        sample_guess_2 = Guess(sample_clue_2, "SPACE", 6)
        sample_guess_3 = Guess(sample_clue_3, "IDEA", 5)

        self.assertEqual(None, collide(sample_guess, sample_guess_2))
        self.assertEqual(None, collide(sample_guess_3, sample_guess_2))
        self.assertEqual((sample_guess, sample_guess_3),
                         collide(sample_guess, sample_guess_3))
示例#3
0
    def test_check_fit(self):
        sample_clue = Clue(0, 2, 4, "D", "", 0, "KIND")
        sample_clue_2 = Clue(0, 3, 5, "D", "", 1, "SPACE")
        sample_clue_3 = Clue(2, 0, 4, "A", "", 2, "IDEA")

        grid = init_grid([sample_clue, sample_clue_2, sample_clue_3], 5)

        sample_guess = Guess(sample_clue, "KIND", 4)
        sample_guess_2 = Guess(sample_clue_2, "SPACE", 6)
        sample_guess_3 = Guess(sample_clue_3, "IDEASS", 5)

        self.assertEqual("fit", check_fit(grid, sample_guess))
        self.assertEqual("fit", check_fit(grid, sample_guess_2))
        self.assertEqual("bounds_error", check_fit(grid, sample_guess_3))
示例#4
0
    def test_find_best_set(self):
        sample_clue = Clue(0, 2, 4, "D", "", 0, "KIND")
        sample_clue_2 = Clue(0, 3, 5, "D", "", 1, "SPACE")
        sample_clue_3 = Clue(2, 0, 4, "A", "", 2, "IDEA")

        sample_guess = Guess(sample_clue, "KIND", 4)
        sample_guess_2 = Guess(sample_clue_2, "SPACE", 6)
        sample_guess_3 = Guess(sample_clue_3, "IDEA", 5)

        guess_set = set()
        guess_set.add(sample_guess)
        guess_set.add(sample_guess_2)
        returned_set = find_best_guess_set(guess_set, sample_guess_3)

        self.assertEqual(set([sample_guess_2, sample_guess_3]), returned_set)
示例#5
0
def gameMain():
    word = Word('words.txt')
    guess = Guess(word.randFromDB())
    hangman = Hangman()

    while hangman.remainingLives > 0:

        display = hangman.currentShape()
        print(display)
        display = guess.displayCurrent()
        print('Current: ' + display)
        display = guess.displayGuessed()
        print('Already Used: ' + display)

        guessedChar = input('Select a letter: ')
        if len(guessedChar) != 1:
            print('One character at a time!')
            continue
        if guessedChar in guess.guessedChars:
            print('You already guessed \"' + guessedChar + '\"')
            continue

        success = guess.guess(guessedChar)
        if success == False:
            hangman.decreaseLife()

        if guess.finished() == True:
            print('**** ' + guess.displayCurrent() + ' ****')
            print('Success')
            break
    else:
        print(hangman.currentShape())
        print('word [' + guess.secretWord + ']')
        print('guess [' + guess.displayCurrent() + ']')
        print('Fail')
示例#6
0
    def main(self):
        game = Guess()
        game.setMaxTarget(sys.argv)
        playAgain = "y"
        regexYes = re.compile(r"^(y|yes)$")

        while regexYes.search(playAgain) != None:
            game.setTarget()
            print(
                "\nI've chosen a number between 1 and %d inclusive. You guess it..."
                % (game.max()))
            nTurns = 0
            guess = -1
            while guess != game.target():
                nTurns += 1
                padPrompt = " " * (len(str(999)) - len(str(nTurns)))
                s = "%s[%d] Enter your guess (1-%d inclusive): " % (
                    padPrompt, nTurns, game.max())
                guess = self.getGuess(s)
                #print("target: %d;  guess: %d" % (game.target(), guess))

                (success, msg) = game.isSuccessful(guess, nTurns)
                print(msg)
            playAgain = input(
                "Do you want to play again? (y/n) ").strip().lower()
示例#7
0
def gameMain():
    word = Word('words.txt')
    guess = Guess(word.randFromDB())

    finished = False
    hangman = Hangman()
    maxTries = hangman.getLife()

    while guess.numTries < maxTries:

        display = hangman.get(maxTries - guess.numTries)
        print(display)
        guess.display()

        guessedChar = input('Select a letter: ')

        finished = guess.guess(guessedChar)
        if finished:
            break

    if finished:
        print('Success')
    else:
        print(hangman.get(0))
        print('word [' + guess.word + ']')
        print("Guess:", end=" ")
        for i in range(len(guess.current)):
            print(guess.current[i], end=" ")
        print()
        print('Fail')
示例#8
0
def gameMain():
    word = Word('words.txt')
    guess = Guess(word.randFromDB())
    hangman = Hangman()
    UI = TextUI(guess, hangman)

    while hangman.getLife() > 0:
        guessedChar = input("Select a letter: ")
        # 잘못된 입력에 대한 처리
        if len(guessedChar) is not 1:
            UI.errorPrint("""
            =================================
            =====Input just one character====
            =================================""")
            continue
        if guessedChar in guess.guessedList:
            UI.errorPrint("""
            =================================
            =====Input another character=====
            =================================""")
            continue
        # Guess결과에 따른 처리
        result = guess.guess(guessedChar)
        if result is 1:
            break
        if result is 0:
            hangman.minusLife()
        UI.display()
    UI.display()
    UI.endOfGame(hangman.getLife())
示例#9
0
def gameMain():
    word = Word('words.txt')
    guess = Guess(word.randFromDB())

    finished = False
    hangman = Hangman()
    maxTries = hangman.getLife()

    while guess.numTries < maxTries:

        display = hangman.get(maxTries - guess.numTries)
        print(display)
        guess.display()

        guessedChar = input('Select a letter: ')
        if len(guessedChar) != 1:
            print('One character at a time!')
            continue
        if guessedChar in guess.guessedChars:
            print('You already guessed \"' + guessedChar + '\"')
            continue

        finished = guess.guess(guessedChar)
        if finished == True:
            break

    if finished == True:
        print('Success')
    else:
        print(hangman.get(0))
        print('word [' + guess.secretWord + ']')
        print('guess [' + guess.currentWord + ']')
        print('Fail')
示例#10
0
def gameMain():
    word = Word('words.txt')
    guess = Guess(word.randFromDB())

    hangman = Hangman()
    maxTries = hangman.getLife()

    while (maxTries - guess.numTries):

        display = hangman.get(maxTries - guess.numTries)
        print(display)
        guess.display()

        guessedChar = input("Select a letter:")
        if len(guessedChar) != 1:
            print("One character at a time!")
            continue
        if guessedChar in guess.guessedChars:
            print("You already guessed \' %c \' " % (guessedChar))
            continue

        if guess.guess(guessedChar) == True:
            print("Success!")
            break

    if guess.guess(guessedChar) == False:
        print(hangman.get(0))
        print("word [ %s ]" % (guess.secretWord))
        print("guess [ %s ]" % (guess.currentStatus))
        print('Fail')
示例#11
0
    def gameloop():
        #步驟一:印出提示訊息
        print("請猜出 0 到 9 之間的正整數...")
        print("總共有三次機會猜出正確數字...")
        print("準備好了嗎...")

        #步驟二:建立計算核心物件
        g = Guess()

        #步驟三:遊戲的主要迴圈
        count = 0  #記錄次數
        flag = 0  #記錄答對與否
        while count < 3:
            count += 1
            n = input("請輸入:")

            result = g.answer(int(n))
            if result == 0:
                #步驟四之一:答對
                print("答對!")
                print("你猜了" + str(count) + "次...")
                flag = 1
            elif result == 1:
                print("大一點!")
            elif result == 2:
                print("小一點!")
            else:
                print("不正確的輸入...")

            if flag == 1:
                break

        #步驟四之二:沒有答對
        if flag == 0:
            print("猜了三次也沒猜對,答案是" + str(g.number) + "。")
示例#12
0
def gameMain():
    word = Word('words.txt')
    guess = Guess(word.randFromDB())  # 랜덤하게 단어선택

    finished = False
    hangman = Hangman()
    maxTries = hangman.getLife()  # 목숨의 개수를 초기화 시킴

    while guess.numTries < maxTries:  # 목숨이 몇개 남았는지 체크해줌

        display = hangman.get(maxTries - guess.numTries)
        print(display)
        guess.display()

        guessedChar = input('Select a letter: ')
        if len(guessedChar) != 1:  # 한글자가 아니면
            print('One character at a time!')
            continue
        if guessedChar in guess.guessedChars:  # 이미 사용한 문자라면
            print('You already guessed \"' + guessedChar + '\"')
            continue

        finished = guess.guess(guessedChar)
        if finished == True:
            break

    if finished == True:
        print('Success')
        print('word : ' + guess.secretWord)
    else:
        print(hangman.get(0))
        print('word [' + guess.secretWord + ']')
        print('guess [' + guess.currentStatus + ']')
        print('Fail')
示例#13
0
def gameMain():
    word = Word('words.txt')
    guess = Guess(word.randFromDB())
    hangman = Hangman()

    while hangman.remainingLives > 0:

        display = hangman.currentShape()
        print(display)
        display = guess.displayCurrent()
        print('Current: ' + display)
        display = guess.displayGuessed()
        print('Already Used: ' + display)

        success = guess.guess(getChar())
        if success == 1:
            continue
        elif success == 2:
            continue
        elif success == False:
            hangman.decreaseLife()
        
        if guess.finished():
            break

    if guess.finished() == True:
        print('**** ' + guess.displayCurrent() + ' ****')
        print('Success')
    else:
        print(hangman.currentShape())
        print('word [' + guess.secretWord + ']')
        print('guess [' + guess.displayCurrent() + ']')
        print('Fail')
示例#14
0
    def test_matrix_score(self):
        sample_clue = Clue(0, 2, 4, "D", "", 0, "KIND")
        sample_clue_2 = Clue(0, 3, 5, "D", "", 1, "SPACE")
        sample_clue_3 = Clue(2, 0, 4, "A", "", 2, "IDEA")

        sample_guess = Guess(sample_clue, "KIND", 4)
        sample_guess_2 = Guess(sample_clue_2, "SPACE", 6)
        sample_guess_3 = Guess(sample_clue_3, "IDEA", 5)

        grid_empty = init_grid([sample_clue, sample_clue_2, sample_clue_3], 5)
        grid_from_guesses = make_grid_from_guesses(
            [sample_guess, sample_guess_2, sample_guess_3],
            [sample_clue, sample_clue_2, sample_clue_3], 5)

        self.assertEqual(0, matrix_score(grid_empty))
        self.assertEqual(11 / 25, matrix_score(grid_from_guesses))
def get_blank_answers(clue:Clue,limit=10,words_only=True):
    """Takes in a fill-in-the-blank clue and returns a list of possible answers from Google"""
    
    if clue not in google_cache.keys():
        # quote wrap and google
        q = '"{}"'.format(clue.get_description().lower())
        results = " ".join(i for i in search_google(q))

        # regex search only for the words immediately before and after the blank
        q_split = q.split(" ")
        q_around_blank = " ".join([q_split[q_split.index("*")-1],"*",q_split[q_split.index("*")+1]])
        regex = q_around_blank.replace("*",".{{{}}}".format(clue.get_length())).strip('"')
        r = re.compile(regex)

        matches = re.findall(r,results)
        words = []
        for match in matches:
            for word in match.split(" "):
                if word.lower() not in regex.split(" "):
                    words.append(word)
        scores = score_words(words)
        ret = [Guess(clue, word, score) for word, score in scores]
        google_cache[clue] = ret
        return ret[:limit]
    else:
        return google_cache[clue][:limit]
    def __init__(self):
        self.g = Guess()
        self.count = 0
        self.flag = 0

        self.app = View(master=Tk())
        self.app.guess["command"] = self.guess
        self.app.again["command"] = self.again
        self.app.mainloop()
示例#17
0
    def startGame(self):
        self.hangman = Hangman()
        self.guess = Guess(self.word.randFromDB())
        self.gameOver = False

        self.hangmanWindow.setPlaceholderText(self.hangman.currentShape())
        self.currentWord.setText(self.guess.displayCurrent())
        self.guessedChars.setText(self.guess.displayGuessed())
        self.message.clear()
示例#18
0
    def startGame(self):
        self.hangman = Hangman()
        self.guess = Guess(self.word.randFromDB(2))
        self.gameOver = False
        self.pixelofword = len(self.guess.secretWord) * 20
        self.currentWord.setFixedWidth(self.pixelofword)

        self.hangmanWindow.setPlaceholderText(self.hangman.currentShape())
        self.currentWord.setText(self.guess.displayCurrent())
        self.guessedChars.setText(self.guess.displayGuessed())
        self.message.clear()
示例#19
0
    def startGame(self):
        self.hangman = Hangman()
        self.guess = Guess(self.word.randFromDB(5))
        font = self.currentWord.font()
        self.currentWord.setFixedWidth((font.pointSize() + 5) * len(self.guess.displaySecretWord()))
        self.gameOver = False

        self.hangmanWindow.setPlaceholderText(self.hangman.currentShape())
        self.currentWord.setText(self.guess.displayCurrent())
        self.guessedChars.setText(self.guess.displayGuessed())
        self.message.clear()
示例#20
0
def gameMain():
    '''게임 구동 과정'''

    # 파일에 있는 단어 정리 및 갯수 알려주기
    word = Word('aabbcc.txt')

    # 파일안에 있는 단어 랜덤적으로 가져온다.
    guess = Guess(word.randFromDB())

    # 처음에는 단어가 완성이 안돼있으니 False 출력
    finished = False

    # 목숨갯수(maxTries = 6)초기화
    hangman = Hangman()
    maxTries = hangman.getLife()

    # numTries(현재 남은 목숨갯수)가 6보다 크거나 같을 때가지 실행
    while guess.numTries < maxTries:

        # 시각적으로 행맨을 보여준다 (남은 목숨갯수에 맞게)
        # 6 -> 0
        display = hangman.get(maxTries - guess.numTries)
        print(display)
        guess.display()

        guessedChar = input('Select a letter: ')

        # 알파벳 한개만 적기 #
        if len(guessedChar) != 1:
            print('One character at a time!')
            continue
        # guessedChars는 이미적은 알파벳을 모아 놓은 곳
        if guessedChar in guess.guessedChars:
            print('You already guessed \"' + guessedChar + '\"')
            continue

        # 입력된 알파벳이 랜덤단어안에 있는지 확인
        # 단어가 완성 되었는지
        finished = guess.guess(guessedChar)
        if finished == True:
            break

    # 알파벳이 존재한다면 성공
    if finished == True:
        print('Success')

    # 만약 제안된 기회 안에 단어를 완성하지못했다면
    else:
        # 매달린 남자 보여주기
        print(hangman.get(0))
        #사용한 알파벳, 기회가용횟수, 실패
        print('word was [' + guess.secretWord + ']')
        print('guess [' + guess.currentStatus + ']')
        print('Fail')
示例#21
0
    def __init__(self):
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(self.settings.screen_size)
        pygame.display.set_caption("Guess Number")

        self.buttons = pygame.sprite.Group()
        self.numbers = pygame.sprite.Group()
        self.guess = Guess(self.settings)

        self.functions = Functions(self.settings, self.screen, self.buttons,
                                   self.numbers, self.guess)
示例#22
0
    def newGameClicked(self):
        from word import Word
        word = Word('words.txt')
        self.GuessObject = Guess(word.randFromDB())
        self.hangmanObject = Hangman()

        self.guessButton.setEnabled(True)
        self.newGameButton.setEnabled(False)

        self.charInput.clear()
        self.message.clear()
        self.currentWord.clear()
        self.display()
def gameMain():
    word = Word('words.txt')
    #guess 는 Guess 클래스에 랜덤으로 단어 하나를 인자로 던진 것
    guess = Guess(word.randFromDB())

    finished = False
    hangman = Hangman()
    #목숨의 개수를 초기화
    maxTries = hangman.getLife()
    #실패한 횟수가 목숨보다 적으면 계속 실행
    while guess.numTries < maxTries:
        #display라는 변수를 통해 만들어서 행맨 모양을 불러옴
        display = hangman.get(maxTries - guess.numTries)
        #행맨 모양 출력
        print(display)
        #Current 와 Tries 출력
        guess.display()
        #입력한 문자를 guessedChar라고 함
        guessedChar = input('Select a letter: ')
        #입력한 문자가 한글자가 아니라면
        if len(guessedChar) != 1:
            print('One character at a time!')
            continue
        #입력한 문자가 대문자라면
        if 65 <= ord(guessedChar) <= 90:
            #소문자로 변경
            guessedChar = chr(ord(guessedChar) + 32)
        #입력한 문자가 이미 입력했던 문자라면
        if guessedChar in guess.guessedChars:
            print('You already guessed \"' + guessedChar + '\"')
            continue
        #알파벳 이외의 다른 모든 경우의 수를 차단
        if ord(guessedChar) <= 64 or 91 <= ord(
                guessedChar) <= 96 or 123 <= ord(guessedChar):
            print('Please enter the alphabet!')
            continue
        #guess 모듈로 넘어가서 입력한 문자에 대해 처리
        finished = guess.guess(guessedChar)
        #단어가 완성되었을 때 while 탈출
        if finished == True:
            break

    if finished == True:
        print('Success')
    #단어가 완성되어서 탈출한게 아니라 목숨의 개수가 다달아서 False인 상태에서 while문을 빠져나온 경우
    else:
        print(hangman.get(0))
        print('word [' + guess.secretWord + ']')
        print('guess [' + ''.join(guess.currentStatus) + ']')
        print('Fail')
示例#24
0
 def process_guess(self, guess):
     if len(guess) != self.num_digits:
         return self.get_json_response(
             status='error',
             message=f'Guess must be {self.num_digits} digits long.')
     for n in guess:
         if n not in self.allowed_digits:
             return self.get_json_response(
                 status='error',
                 message=f'Only {self.get_digits()} are allowed.')
     self.used_guesses += 1
     hint = Guess(self.secret, guess)
     self.history.append(hint)
     return self.get_response(hint)
示例#25
0
    def startGame(self):
        self.hangman = Hangman()
        self.guess = Guess(self.word.randFromDB(20))
        self.gameOver = False

        if len(self.guess.secretWord) >=10:
            font = self.currentWord.font()
            font.setPointSize(font.pointSize())
            self.currentWord.setFont(font)


        self.hangmanWindow.setPlaceholderText(self.hangman.currentShape())
        self.currentWord.setText(self.guess.displayCurrent())
        self.guessedChars.setText(self.guess.displayGuessed())
        self.message.clear()
示例#26
0
def get_answers(clue: Clue, limit=10):
    """Takes in a Clue object and returns a list of words (optionally associated with scores) which
        are potential answers to the given clue."""

    params = {}
    length = clue.get_length()

    params["ml"] = clue.description
    params["sp"] = "?" * clue.length

    results = []
    for item in request(params)[:limit]:
        guess = Guess(clue, item["word"], item["score"])
        results.append(guess)

    return results
示例#27
0
def gameMain():
    word = Word('words.txt')
    guess = Guess(word.randFromDB())

    finished = False
    hangman = Hangman()

    print(hangman.currentShape())
    print(guess.displayGuessed())
    while hangman.is_live():
        guessedChar = input('Select a letter: ')
        system('clear')
        if len(guessedChar) != 1:
            print(hangman.currentShape())
            print(guess.displayCurrent())
            print("tried : [" + guess.displayGuessed() + "]")
            print('One character at a time!')
            continue
        if guess.is_usedChar(guessedChar):
            print(hangman.currentShape())
            print(guess.displayCurrent())
            print("tried : [" + guess.displayGuessed() + "]")
            print('You already guessed \"' + guessedChar + '\"')
            continue

        correct = guess.guess(guessedChar)
        if not correct:
            hangman.decreaseLife()

        if guess.is_finish():
            finished = True
            break

        print(hangman.currentShape())
        print(guess.displayCurrent())
        print("tried : [" + guess.displayGuessed() + "]")


    if finished:
        print(hangman.currentShape())
        print('Success' + '[' + guess.displayGuessWord() + ']')
    else:
        print(hangman.currentShape())
        print('word [' + guess.displayGuessWord() + ']')
        print('guess [' + guess.displayCurrent() + ']')
        print('Fail')
示例#28
0
文件: game.py 项目: minjj0905/SWP2_8
def gameMain():
    word = Word('words.txt')
    guess = Guess(word.randFromDB())

    finished = False
    hangman = Hangman()

    while hangman.remainingLives > 0:

        display = hangman.currentShape()
        print(display)
        guess.displayCurrent()
        print("used letter: ")
        print()
        for i in string.ascii_lowercase:
            if i in guess.guessedChars:
                print(colored(i, 'red'), end=' ')
            else:
                print(colored(i, 'green'), end=' ')
        print()
        print()

        guessedChar = input('Select a letter: ')
        if len(guessedChar) != 1:
            print('One character at a time!')
            continue
        if guessedChar in guess.guessedChars:
            print('You already guessed \"' + guessedChar + '\"')
            continue

        success = guess.guess(guessedChar)
        print(success)
        if not success:
            hangman.decreaseLife()
        if guess.finished():
            break

    if guess.finished():
        print(guess.displayCurrent())
        print('Success')
    else:
        print(hangman.currentShape())
        print(guess.secretWord)
        guess.displayCurrent()
        print('Fail')
示例#29
0
    def gameMain():
        word = Word('words.txt')
        guess = Guess(word.randFromDB())

        print('%d words in DB' % word.count)

        finished = False
        hangman = Hangman()

        while hangman.remainingLives > 0:

            display = hangman.currentShape()
            print(display)
            display = guess.displayCurrent()
            print('Current: ' + display)
            display = guess.displayGuessed()
            print('Already Used: ' + display)

            guessedChar = input("Select a Letter: ")

            if len(guessedChar) == 1:
                if 65 <= ord(guessedChar) <= 90 or 97 <= ord(
                        guessedChar) <= 122:
                    if 65 <= ord(guessedChar) <= 90:
                        guessedChar = chr(ord(guessedChar) + 32)
                    if guessedChar not in guess.used_set:
                        success = guess.guess(guessedChar)
                        if not success:
                            hangman.decreaseLife()

            finished = guess.finished()
            if finished:
                break

        if finished:
            print('Success')
            print('word [' + guess.word + ']')
        else:
            print('word [' + guess.word + ']')
            print("Guess:", end=" ")
            for i in range(len(guess.current)):
                print(guess.current[i], end=" ")
            print()
            print('Fail')
示例#30
0
def gameMain():
    word = Word('words.txt')
    guess = Guess(word.randFromDB())  #랜덤 단어 선택

    finished = False
    hangman = Hangman()
    maxTries = hangman.getLife()  #목숨개수 초기화

    while guess.numTries < maxTries:
        # numTries는 추측 실패 횟수
        display = hangman.get(maxTries - guess.numTries)
        print(display)
        guess.display()

        guessedChar = input('Select a letter: ')
        # 입력받은 문자열이 1개의 문자가 아닐 때
        if len(guessedChar) != 1:
            print('One character at a time!')
            continue
        # 입력받은 문자가 이미 이전에 입력받은 것일 떄
        if guessedChar in guess.guessedChars:
            print('You already guessed \"' + guessedChar + '\"')
            continue
        # 입력받은 문자가 a~z가 아닐 때
        if guessedChar < 'a' or guessedChar > 'z':
            print('please enter a character between a and z')
            continue
        #전체 문자 맞추면 while문 break 하고 Success 프린트
        finished = guess.guess(guessedChar)
        if finished == True:
            break

    if finished == True:
        print()
        print(guess.secretWord)
        print('Success!')
        print('You win by trying', guess.numTries, 'Times')
    #허용된 횟수 내에 전체 문자 못 맞추면 hangman.text[0] 출력, 즉 목 매다는 그림 출력
    else:
        print(hangman.get(0))
        print('word [' + guess.secretWord + ']')
        print()
        print('Fail')
        print("The word was", guess.secretWord)