def test_letter_verification(): assert Hangman.letter_verification("a", [], []) == "a" with pytest.raises(OSError): Hangman.letter_verification("a", ["a"], []) with pytest.raises(AttributeError): Hangman.letter_verification(1, [], [])
def test_verify_playfield(): play, playfield_str = Hangman.verify_playfield("word", ["-", "-", "-", "-"], []) assert playfield_str == "- - - -" assert play == True play, playfield_str = Hangman.verify_playfield("word", ["w", "o", "r", "d"], []) assert playfield_str == False assert play == False
def test_get_word(): word, word_dict, playfield_list = Hangman.get_word() assert type(word) == str assert type(word_dict) == dict assert type(playfield_list) == list assert "-" not in word assert len(word) != 0 assert len(word) == len(word_dict) assert len(word) == len(playfield_list) word, word_dict, playfield_list = Hangman.get_word() return word_dict
def start_game(): global user_money """ 사용자에게 다음과 같은 선택지를 제시합니다. 1. Play Blackjack Game 2. Play Bulls and Cows Game 3. Play Hangman Game 4. Play Number Guess Game 5. Quit Casino """ while True: award = 0 menu = input( "무엇을 하시겠습니까? \n\n1. Play Blackjack Game\n2. Play Bulls and Cows Game\n3. Play Hangman Game\n4. Play Number Guess Game\n5. Quit Casino\n" ) if menu == "1": award = Blackjack.play() elif menu == "2": award = Bulls_and_Cows.play() elif menu == "3": award = Hangman.play() elif menu == "4": award = NumberGuessGame.play() elif menu == "5": print("무엇이든 적당히 할 때 가장 즐거운 법입니다. 좋은 시간이셨기를 바랍니다") break else: print("다시 입력해주세요 : ") continue user_money += award print("\n\n\n") print("현재 당신의 재산은 %d천만원입니다!" % user_money)
def test_letter_in_word(): word = "word" word_dict = dict(enumerate(word)) playfield_list = list(''.join(len(word) * "-")) wrong_letters = [] right_letters = [] playfield_list, wrong_letters, right_letters = Hangman.letter_in_word( "w", word_dict, playfield_list, wrong_letters, right_letters) assert playfield_list == ["w", "-", "-", "-"] assert wrong_letters == [] assert right_letters == ["w"] playfield_list, wrong_letters, right_letters = Hangman.letter_in_word( "q", word_dict, playfield_list, wrong_letters, right_letters) assert playfield_list == ["w", "-", "-", "-"] assert wrong_letters == ["q"] assert right_letters == ["w"]
def test_check_game_end(self): test_word_guessed_count = numpy.array([1, 4, 2, 1, 6, 10, 11, -3, 9, 2]) test_word_length = numpy.array([2, 12, 3, 5, 3, 2, 11, 10, 0, 1]) test_attempts = numpy.array([5, 2, 0, -2, 4, 1, 0, 2, 3, 1]) test_answers = numpy.array(['continue', 'continue', 'loose', 'loose', 'win', 'win', 'loose', 'continue', 'win', 'win']) for i in range(9): self.assertEqual(test_answers[i], Hangman.check_game_end(test_word_guessed_count[i], test_word_length[i], test_attempts[i]))
def runHangman(display): game = Hangman.Hangman(display) while (game.input != 27): game.update() game.display.refresh() game.input = game.display.getKey()
def test_is_letter_correct(self): test_letters = numpy.array(['fas', '6', 'F', ' ', 'a', 'n', 'v', 'r', 'v']) letter_list_already_guessed = numpy.array([[''], [''], [''], [''], ['a'], ['a', 'v', 'c', 'y'], ['a'], ['a'], ['a', 'n', 'v', 'r']]) correct_answer = numpy.array([False, False, False, False, False, True, True, True, False]) for i in range(9): self.assertEqual(correct_answer[i], Hangman.is_letter_correct(test_letters[i], letter_list_already_guessed[i]))
def start_new_game(): word_selector_id = random.randint(1, NUMBER_OF_ROWS) conn = mysql.connect() cursor = mysql.get_db().cursor() cursor.execute( "SELECT word, word_length FROM dev.hang_man_tbl where idhang_man=(%s)", (word_selector_id)) row = list(cursor.fetchone()) global hmGame hmGame = Hangman.NewHangmanGame(word_selector_id, row[0], row[1]) conn.close() return render_template('new_game.html', hm=hmGame)
def main(): print("===HANGMAN===") print("By Weiye Yang") game = Hangman.Hangman() while True: victory = playHangman(game) if victory: print("You won!") else: print("You lost.") print("The answer was {0}.".format(game.answer)) choice = playAgain() if not choice: break
# Made by Jasque Saydyk # Lab 13 - Hangman # Section 2, May 8, 2017 # Description - Main game loop the game exists in from Hangman import * from HangmanGUI import * if __name__ == "__main__": filehandle = open("corncob_lowercase.txt", "r") game = Hangman(filehandle) filehandle.close() gui = HangmanGUI("background.png", game.getCurrentWord()) while(True): letter = gui.takeInput() # Takes input and adds it to game try: choice = game.inputLetter(letter) usedLetters = game.getUsedLetters() gui.updateIncorrectLetters("".join(usedLetters)) if choice is True: gui.updateWord(game.getCurrentWord()) except ValueError: print("Error, try again") # Draw Hangman as more mistakes are made
''' This module is for you to use to test your implemention of the functions in Hangman.py @author: ksm ''' import Hangman if __name__ == '__main__': ''' print('Testing createDisplayString') lettersGuessed = ['a', 'e', 'i', 'o', 's', 'u'] misses = 4 hangmanWord = list('s___oo_') s = Hangman.createDisplayString(lettersGuessed, misses, hangmanWord) print(s) print() print('Testing updateHangmanWord') guessedLetter = 'a' secretWord = 'cat' hangmanWord = ['c', '_', '_'] expected = ['c', 'a', '_'] print('Next line should be: ' + str(expected)) print(Hangman.updateHangmanWord(guessedLetter, secretWord, hangmanWord)) ''' print(Hangman.runGame('lowerwords.txt'))
def test_chooseWord(self): actual = Hangman.chooseWord("a") expected = True self.assertTrue(actual, "Word is chosen")
def test_chooseWord(self): expected = False actual = Hangman.chooseWord("a") self.assertTrue(' ',"Word is not chosen")
import Hangman import Hangman_Learner import MongoDB_Access as mongo from tqdm import tqdm ##GLOBALS## #RUNS = 0 WORD_LIST = mongo.get_dictionary_words() for i in tqdm(range(10000)): IS_GAME_RUNNING = True # ROUNDS = 1 hangman = Hangman.Hangman(WORD_LIST) learner = Hangman_Learner.Hangman_Learner() while IS_GAME_RUNNING: # print("---------------") # print("HANGMAN OUTPUT") # print("ROUND " + str(ROUNDS)) # print("*for testing purposes... WORD: " + hangman.word) # print("REMAINING GUESSES: " + str(hangman.guesses)) # print("PREVIOUS GUESSES: " + str(hangman.previous_guesses)) # print("ENCRYPTED WORD: " + hangman.encrypted_word) # print("~~~~~") learner.think() guess = learner.guess() if guess == "Skip": break # print("GUESSED LETTER: " + guess)
def main(): ''' The main block of the program which runs the entire display. ''' pygame.init() # Initialize pygame hangman = Hangman.Hangman() global m m = "" while True: try: random_word = hangman.rand() break except Exception as e: print(e) white = (255, 255, 255) red = (255, 0, 0) black = (0, 0, 0) blue = (0, 0, 255) green = (0, 255, 0) global gameDisplay gameDisplay = pygame.display.set_mode( (800, 600)) # Pass a tuple as a parameter display_width = 800 display_height = 600 pygame.display.set_caption("Hangman") pygame.display.update() # Update the specific modification clock = pygame.time.Clock() gameExit = False while not gameExit: message("Hangman", blue, display_width / 7, display_height / 7, 50) pygame.display.update() message("Deduce the word...", white, display_width / 4, display_height / 4, 30) pygame.display.update() subprocess.call(["espeak", "Deduce the word"]) hangman.str1 = hangman.initialize(random_word) message(hangman.str1, white, display_width / 2, display_height / 2, 40, True) pygame.display.update() m = hangman.str1 hangman.str1 = "" while hangman.counter < 20: subprocess.call( ["espeak", str(20 - hangman.counter) + " trials left"]) hangman.counter = hangman.counter + 1 hangman.str1 = "" letter = "" print("Enter letter: ") with hangman.lock: record = recorder.Recorder("../../../Language_Models/", LIB_FILE="characters", SILENCE=1, TRIALS=1, DECODE=True) record.start() r = open('./test.hyp', 'r') arr = r.read().split(" ") letter = arr[0] print(letter) lt = letter.lower() r.close() try: hangman.string = str( hangman.check(hangman.str1, lt, random_word)) except Exception as e: print(e) hangman.str1 = "" for j in range(0, len(hangman.string)): hangman.str1 = hangman.str1 + hangman.string[j] + " " message(m, black, display_width / 2, display_height / 2, 40, True, black) pygame.display.update() message(hangman.str1, white, display_width / 2, display_height / 2, 40, True) pygame.display.update() m = hangman.str1 if hangman.string == random_word: message("You Win", green, display_width / 2, (3 * display_height) / 4, 45, True) pygame.display.update() subprocess.call(["espeak", "You win"]) gameExit = True break elif hangman.counter == 20: subprocess.call(["espeak", "You lose"]) with hangman.lock: subprocess.call(["espeak", "The answer is " + random_word]) message("You Lose...Answer is: " + random_word, red, display_width / 2, (3 * display_height) / 4, 45, True) pygame.display.update() gameExit = True message( "Score out of 10: " + str(hangman.score(hangman.string, random_word)), green, display_width / 2, (5 * display_height) / 6, 40, True) pygame.display.update() clock.tick(20) subprocess.call([ "espeak", "-s", "125", " Options are 1: Resume and 2: Start another game" ]) pygame.quit() quit()
import sys import play21 import Hangman import guess_num import comp_guess while True: choice = "" choice = input( "B for Black Jack, N to Let Comp Guess, H for Hangman, G to Guess the Number, or Q to quit?" ).upper() if choice == "B": play21.play_game() elif choice == "H": Hangman.hangman() elif choice == "N": comp_guess.comp_guess_game() elif choice == "G": guess_num.guess() elif choice == "Q": print("Goodbye!") sys.exit() else: print("Try again.")
''' This module is for you to use to test your implemention of the functions in Hangman.py @author: ksm ''' import random import Hangman if __name__ == '__main__': print('Testing createDisplayString') lettersGuessed = ['a', 'e', 'i', 'o', 's', 'u'] misses = 4 hangmanWord = list('s___oo_') s = Hangman.createDisplayString(lettersGuessed, misses, hangmanWord) print(s) print() print('Testing updateHangmanWord') guessedLetter = 'a' secretWord = 'cat' hangmanWord = ['c', '_', '_'] expected = ['c', 'a', '_'] print('Next line should be: ' + str(expected)) print(Hangman.updateHangmanWord(guessedLetter, secretWord, hangmanWord)) print() print('Testing createDisplayString') lettersGuessed = ['a', 'e', 'i', 'o', 's', 'u'] missesLeft = 4 hangmanWord = ['s', '_', '_', '_', 'o', 'o', '_'] print(Hangman.createDisplayString(lettersGuessed, missesLeft, hangmanWord))
def playMatch(Intentos, listapalabras, palaacer, puntos): #Cada playmach es una palabra incognitaSolucion, listapalabras = DarIncongnita.SeleccionPalabra( listapalabras) incognitaGuion = "" incognitaGuion = MeterGuiones.MeterGuiones(incognitaSolucion) Gano = False Perdio = False Intentos = Intentos lista1 = [] while not (Gano) and not (Perdio): Limpiar.Limpiar() print("puntos: ", puntos) Hangman.hangman(Intentos, incognitaGuion) print("") print( "═══════Letras Incorrectas══════════════════════════════════════════" ) print(" ", lista1[0:7]) print( "═══════════════════════════════════════════════════════════════════" ) if Intentos == 0: Perdio = True if not Perdio: letraMenu = MenuPartida.MenuPartida(palaacer, incognitaSolucion, incognitaGuion) #Si ingreso la letra if letraMenu[0] == '1': letra = letraMenu[1] #si esta bien la letra se agrega if Control_LetraEnPalabra.Control_LetraEnPalabra( letra, incognitaSolucion): incognitaGuion = MeterLetra.MeterLetra( incognitaGuion, letra, Control_LetraEnPalabra.Control_LetraEnPalabra( letra, incognitaSolucion)) #Si esta mal se resta el intento y agrega en el historial de fallo la letra else: Intentos = Intentos - 1 lista1.append(letra) print("") #Si pidio pista elif letraMenu[0] == '2': letra = letraMenu[1] incognitaGuion = MeterLetra.MeterLetra( incognitaGuion, letra, Control_LetraEnPalabra.Control_LetraEnPalabra( letra, incognitaSolucion)) Intentos = Intentos - 1 #Si se ridió else: Perdio = True #Si no hay mas guiones es por que gano if incognitaGuion.count("_") == 0: Gano = True if Gano: Hangman.hangman(Intentos, incognitaGuion) time.sleep(1) palaacer.append(incognitaSolucion) mensaje_gano() input() return [True, Intentos], listapalabras, palaacer elif Perdio: mensaje_predio2() print("La respuesta FUE: ", incognitaSolucion) return [False, 0], listapalabras, palaacer
''' Created on Nov 18, 2015 @author: eltakwaa ''' import Hangman if __name__ == '__main__': pass print("-----Hangman game-----") print("This is a guessing game. You have to guess the letter of a word.") print("If it's a correct guess then the letter will appear in its position.") print("if no then you will lose one life") print("***You have 6 available guesses***") print("Press: ") print(" (1) If you want to play.") print(" (2) Exit.") Press = input("Choice: ") Hangman.CallHangmanGame(Press)
def test_gibbet_build(): assert Hangman.gibbet_build(["q", "e"]) == """
def test_letter_positions_in_string(self): test_letters = numpy.array(['a', 'b', 'asd', 'r']) correct_answer = numpy.array([[0, 3], [], [], [4]]) for i in range(4): self.assertEqual(correct_answer[i], Hangman.letter_positions_in_string('anvar', test_letters[i]))
"You are in cRiemistry. There is a passage to the west, north, and east.", 5, 7, None, 4 ] room_list.append(room) room = [ "You are in Lunch. There is a passage to the west.", None, None, None, 6 ] room_list.append(room) current_room = 0 while done != 'quit': #if statements to assign rooms to games if current_room == 5: Hangman.main() elif current_room == 7: done = FoodFight.food_fight(done) elif current_room == 3: Minesweeper.playgame() #if statements to ask where the user wants to go if done != 'quit': print(room_list[current_room][0]) direction = input("What direction would you like to go? ") print('\n') if direction == 'n': next_room = room_list[current_room][1] if next_room == None:
def clear_history(game_history): game_history = [] def session_history(game_history): for record in game_history: print(record) user_input = input('Would you like to clear the history? (Y/N)') if user_input == 'Y': clear_history(game_history) main_menu_dict = {'1':'Hangman', '2':'Guess My Number', '3':'Yohaku','H':'Session History', 'Q':'Quit'} game_history = [] while (True): user_input = '' print_main_menu(main_menu_dict) while not (user_input.strip() in main_menu_dict): user_input = input('Enter the numer for the game you would like to play. ') if user_input.strip() == 'Q': break if user_input.strip() == 'H': session_history(game_history) continue if user_input.strip() == '1': game = Hangman.Hangman() elif user_input.strip() == '2': game = GuessMyNumber.GuessMyNumber() elif user_input.strip() == '3': game = Yohaku.Yohaku() game.run_game() game_history.append(game)
def __init__(self, database): self.hangman = Hangman() self.database = database
class GameInstance: def __init__(self, database): self.hangman = Hangman() self.database = database def showUI(self, bIsSurvived): if (bIsSurvived): print("Tries: " + str(self.hangman.get_max_life() - self.life)) print("Wrong Answers: " + str(self.wrong_answer)) print(self.hangman.get_character(self.life)) else: print("Your dead!") print("The answer was \"" + self.word + "\"") player_input = input( "Input( \"0\" to start new game, \"1\" to finish game) : ") return player_input def execute(self): bisRunning = True self.reset() while (bisRunning): bIsSurvived = self.life > 0 player_input = self.showUI(bIsSurvived) if (player_input == "0"): self.reset() elif (player_input == "1"): bisRunning = False elif (player_input.isalpha() and len(player_input) == 1 and bIsSurvived): self.input_sentence(player_input) print("Current Answer: " + self.solved) else: print("Wrong input! try again!") def reset(self): self.life = self.hangman.get_max_life() self.word = self.database.pick_random_word() self.solved = "_ " * (len(self.word)) self.wrong_answer = [] print(self.word) def input_sentence(self, sentence): founded_list = findAll(self.word, sentence) if (len(founded_list) == 0): self.decrease_life() if (not (sentence in self.wrong_answer)): self.wrong_answer.append(sentence) else: solved_list = self.solved.split() for idx in founded_list: solved_list[idx] = sentence self.solved = " ".join(solved_list) def decrease_life(self): self.life -= 1 def get_current_life(self): return self.life def get_current_word(self): return self.word
import Hangman word = input("問題を入力してください:") Hangman.hangman(word)