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) + "。")
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')
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())
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')
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')
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()
class MainDish: def __init__(self): self.button_pin = 33 GPIO.setmode(GPIO.BOARD) GPIO.setup(self.button_pin, GPIO.IN) GPIO.add_event_detect(self.button_pin, GPIO.FALLING) # img 폴더 안에 있던 이미지 모두 삭제 for file in os.scandir('../data/img'): os.remove(file.path) for file in os.scandir('../data/board_img'): os.remove(file.path) # 웹캠 사용해서 식판 스캔 self.cap = cv2.VideoCapture(-1) self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) ret, self.img = self.cap.read() cv2.imwrite('../data/board_img/Scanned_image.jpg',self.img, params=[cv2.IMWRITE_JPEG_QUALITY,70]) self.cap.release() # 젓가락의 위치 self.Cx, self.Cy = 0, 0 # keras 미리 로딩 self.guess = Guess() # 모든 클래스의 객체생성 # 1. 급식판 좌표 self.board = Board() self.board.get_target_area() self.board.board_frgm_board() # 3. keras로 음식 맞추기 self.guess.realGuess() # 일단 급식판에 무슨 음식이 있는지 학습 self.answer = self.guess.matchFood(self.Cx, self.Cy, self.board.box_x, self.board.box_y) def goingOn(self): # 여기 callback으로 matchfood 넣을지 고민 t = Tracker() Tracker_thread = Thread(target = t.track_point) Tracker_thread.start() while (True): if GPIO.event_detected(self.button_pin): self.Cx , self.Cy = t.get_track_point() # 젓가락의 위치랑 이미지의 픽셀값안에 있나 확인해서 음식명 출력 print(self.Cx , self.Cy) self.answer = self.guess.matchFood(self.Cx, self.Cy, self.board.box_x, self.board.box_y) print(self.answer) sound = Sound(self.answer) GPIO.remove_event_detect(self.button_pin) time.sleep(0.3) GPIO.add_event_detect(self.button_pin, GPIO.FALLING)
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')
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()
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()
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')
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()
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()
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')
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))
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')
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')
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))
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)
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()
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 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')
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: ').lower() # 대문자가 들어와도 소문자로 취급 # []안의 내용을 컴파일하여 정규식 객체를 반환 r = re.compile('[^ ㄱ-ㅣ가-힣]+') #guessedChar에서 공백을 제외한 문자들을 문자열로 반환 result = r.sub('', guessedChar) if guessedChar.isdigit(): print("알파벳을 입력해 주세요.") continue elif guessedChar in result: print("알파벳을 입력해 주세요.") continue 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.currentStatus + ']') print('Fail')
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)
def gameMain(): #Word클래스로 만든 오브젝트 word = Word('words.txt') #guess 는 랜덤 단어로 만든 Guess의 오브젝트 guess = Guess(word.randFromDB()) # finished = False #Hangman의 오브젝트 만들어서 남은생명 hangman = Hangman() #남은생명==리스트 아이템 개수 maxTries = hangman.getLife() #아마 numtries는 실행횟수 일듯@@@@@@@@@ #실행횟수 < 남은생명 일때.. loop 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 #guseedChars는 내가 이미 제시한 알파벳들의 리스트 일듯. if guessedChar in guess.guessedChars: print('You already guessed \"' + guessedChar + '\"') continue #guess()는 해당 알파벳이 단어안에 있으면 위치를기록. #없으면 실패횟수를 증가시킴 #모든글자를 다 맞추었으면 True 아니면 False. 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.currentStatus + ']') print('Fail')
def gameMain(): numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] word = Word('words.txt') #guess에 랜덤단어 저장 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 else: if guessedChar in numbers: print("Not numbers!") 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.word + ']') print('guess [', guess.strcurrent, ']') print('Fail')
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 guessedChar.isalpha() != 1: print('Enter alphabet') continue if len(guessedChar) != 1: ## 만약 사용자가 문자대신 단어를 입력해서 맞으면 success if guessedChar == guess.secretWord: print('genius godgod smart!') finished = True break else: 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.currentStatus + ']') print('Fail')
def gameMain(): #랜덤으로 단어 선택 word = Word('words.txt') guess = Guess(word.randFromDB()) finished = False hangman = Hangman() #목숨의 갯수를 초기화 maxTries = hangman.getLife() while guess.numTries < maxTries: #max display = hangman.get(maxTries - guess.numTries) print(display) guess.display() #lstrip을 넣어서 공백은 자동으로 제거 guessedChar = input('Select a letter: ') if len(guessedChar.lstrip()) != 1: print('One character at a time!') continue if guessedChar.lstrip() in guess.guessedChars: print('You already guessed \"' + guessedChar + '\"') continue # 입력한 문자가 알파벳 소문자가 아니면 오류 if guessedChar.lstrip() not in alphabet: print('Character must be English small letter!') continue finished = guess.guess(guessedChar) if finished == True: break if finished == True: print('Success') print('The answer is '+guess.secretWord) else: print(hangman.get(0)) print('word [' + guess.secretWord + ']') print('guess [' + guess.currentStatus + ']') print('Fail')
def play_game(self): """Battleship Game mechanics.""" turn_count = 0 # print(self.computer_fleet) while not self.done: functions.clear() self.print_game_status() user_guess = input("Please Enter a Guess: ") user_guess = Guess(user_guess) user_guess.check_if_on_board(self.user_board) if user_guess.quit_flag: break self.computer_board.check_damage(user_guess, self.guess_board, self.computer_fleet) turn_count += 1 if self.computer_fleet.all_ships_sank(): msg = "Congratulations you won! It took you {} turns." print(msg.format(turn_count)) self.done = True
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)
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()
def __init__(self, vbi, bitwidth=5.112, gauss_sd=1.1, gauss_sd_offset=2.0, offset_low = 75.0, offset_high = 119.0, thresh_low = 1.1, thresh_high = 2.36, allow_unmatched = True, find=finders.all_headers): # data arrays # vbi is the raw line as an array of 2048 floats self.vbi = vbi # blurring amounts self.gauss_sd = gauss_sd self.gauss_sd_offset = gauss_sd_offset # Offset range to check for signal drift, in samples. # The algorithm will check with sub sample accuracy. # The offset finder is very fast (it uses bisection) # so this range can be relatively large. But not too # large or you get false positives. self.offset_low = offset_low self.offset_high = offset_high # black level of the signal self.black = np.mean(self.vbi[:80]) # Threshold multipliers. The black level of the signal # is derived from the mean of the area before the VBI # begins. This is multiplied by the following factors # to give the low/high thresholds. Anything outside # this range is assumed to be a 0 or a 1. Tweaking these # can improve results, but often at a speed cost. self.thresh_low = self.black*thresh_low self.thresh_high = self.black*thresh_high # Allow vbi.py to emitt packet 0's that don't match # any finder? Set to false when you have finders # for all headers in the data. self.allow_unmatched = allow_unmatched self.finders = find # vbi packet bytewise self._mask0 = np.zeros(42, dtype=np.uint8) self._mask1 = np.zeros(42, dtype=np.uint8) self.g = Guess(bitwidth=bitwidth)
alphabet = "abcdefghijklmnopqrstuvwxyz " # train english matrixes base_matrix = TrigramSpace(alphabet) english_monograms = MonogramMatrix() with open(training_text_file_location, 'r', -1, 'utf-8', 'replace') as training_text: text = training_text.read() normalized_text = utils.normalize(text) base_matrix.learn(normalized_text) english_monograms.learn(normalized_text) # generate initial guess key = SubstitutionKey("Guess key") english_monograms.setCharacterAsMostCommon(' ') guess = Guess(english_monograms.getListOfUniqueCharacters()) guess.randomGuessOneCharacter() guess_mapping = english_monograms.generateMappingBasedOnFrequencies(file_text) guess.setGuess(guess_mapping) key.set(guess.get()) if actual_key: pprint(actual_key) pprint(guess_mapping) print("score: " + str(utils.compare_keys(actual_key, guess_mapping))) current_decryption = key.decrypt(file_text) ciphertext_matrix = TrigramSpace(alphabet) ciphertext_matrix.learn(current_decryption) # compute initial difference & deep copy the key
#!/usr/bin/env python from flask import Flask, render_template, redirect, url_for, session from flask_wtf import Form from wtforms.fields import RadioField, StringField, SubmitField from wtforms.validators import Required from guess import Guess, GuessError app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' game = Guess('Python') game.expand('Python', 'C++', 'Is it interpreted?', False) game.expand('C++', 'Java', 'Does it run on a VM?', True) class YesNoQuestionForm(Form): answer = RadioField('Your answer', choices=[('yes', 'Yes'), ('no', 'No')]) submit = SubmitField('Submit') class LearnForm(Form): language = StringField('What language did you pick?', validators=[Required()]) question = StringField('What is a question that differentiates your ' 'language from mine?', validators=[Required()]) answer = RadioField('What is the answer for your language?', choices=[('yes', 'Yes'), ('no', 'No')]) submit = SubmitField('Submit') @app.route('/')
print("") print("Usage:") print(" python3 encrypt.py <plaintext> <key> <ciphertext>") print(" - <plaintext> The location of the plaintext file to read from") print(" - <key> The location to write the key to") print(" - <ciphertext> The location to write the ciphertext to") sys.exit("") # collect output / input file locations plaintext_filename = sys.argv[1] key_filename = sys.argv[2] ciphertext_filename = sys.argv[3] # generate a random key unique_characters = list("abcdefghijklmnopqrstuvwxyz ") guess = Guess(unique_characters) guess.randomGuessAllCharacters() guess_dictionary = guess.get() key = SubstitutionKey('') key.set(guess_dictionary) # save the key to file with open(key_filename, 'wt') as out: pprint(guess_dictionary, stream=out) # encrypt plaintext plaintext_file = open(plaintext_filename, 'r') plaintext = plaintext_file.read() plaintext_file.close() ciphertext = key.encrypt(plaintext)
def create_guess(self, file_name): mono_matrix = MonogramMatrix(file_name) guess_init = Guess(mono_matrix.getListOfUniqueCharacters()) guess_init.randomGuessOneCharacter() return guess_init.get()
from guess import Guess from monogrammatrix import MonogramMatrix from accuracyofdecryption import AccuracyOfDecryption mono = MonogramMatrix() mono.learn_from_file('training_corpora/english_word_list.txt') mono.setCharacterAsMostCommon(' ') newGuess = Guess(mono.getListOfUniqueCharacters()) newGuess.randomGuessOneCharacter() #monoMapping = mono.generateMappingBasedOnFrequencies('text_pairs/1.ciphertext.txt') #newGuess.setGuess(monoMapping) #print(monoMapping) accOfDec = AccuracyOfDecryption('training_corpora/english_word_list.txt') accurateResultsCount = accOfDec.getCountOfAccurateWords('hi my name is eric shady\ncats\tare what? I taught eminem') print(accurateResultsCount) #print(monoMatrixOfLanguageFrequencies.get()) #can do a bucket for dictionary?
# train english matrixes base_matrix = DigramMatrix("English") english_monograms = MonogramMatrix() with open(training_text_file_location, 'r', -1, 'utf-8', 'replace') as training_text: text = training_text.read() normalized_text = utils.normalize(text) base_matrix.learn(normalized_text) english_monograms.learn(normalized_text) # generate initial guess key = SubstitutionKey("Guess key") english_monograms.setCharacterAsMostCommon(' ') guess = Guess(english_monograms.getListOfUniqueCharacters()) #guess.randomGuessOneCharacter() guess_mapping = english_monograms.generateMappingBasedOnFrequencies(file_text) guess.setGuess(guess_mapping) key.set(guess.get()) if actual_key: pprint(actual_key) pprint(guess_mapping) print("score: " + str(utils.compare_keys(actual_key, guess_mapping))) current_decryption = key.decrypt(file_text) ciphertext_matrix = DigramMatrix("Ciphertext") ciphertext_matrix.learn(current_decryption) # compute initial difference & deep copy the key
class Vbi(object): '''This class represents a line of raw vbi data and all our attempts to decode it.''' possible_bytes = [hammbytes]*2 + [paritybytes]*40 def __init__(self, vbi, bitwidth=5.112, gauss_sd=1.1, gauss_sd_offset=2.0, offset_low = 75.0, offset_high = 119.0, thresh_low = 1.1, thresh_high = 2.36, allow_unmatched = True, find=finders.all_headers): # data arrays # vbi is the raw line as an array of 2048 floats self.vbi = vbi # blurring amounts self.gauss_sd = gauss_sd self.gauss_sd_offset = gauss_sd_offset # Offset range to check for signal drift, in samples. # The algorithm will check with sub sample accuracy. # The offset finder is very fast (it uses bisection) # so this range can be relatively large. But not too # large or you get false positives. self.offset_low = offset_low self.offset_high = offset_high # black level of the signal self.black = np.mean(self.vbi[:80]) # Threshold multipliers. The black level of the signal # is derived from the mean of the area before the VBI # begins. This is multiplied by the following factors # to give the low/high thresholds. Anything outside # this range is assumed to be a 0 or a 1. Tweaking these # can improve results, but often at a speed cost. self.thresh_low = self.black*thresh_low self.thresh_high = self.black*thresh_high # Allow vbi.py to emitt packet 0's that don't match # any finder? Set to false when you have finders # for all headers in the data. self.allow_unmatched = allow_unmatched self.finders = find # vbi packet bytewise self._mask0 = np.zeros(42, dtype=np.uint8) self._mask1 = np.zeros(42, dtype=np.uint8) self.g = Guess(bitwidth=bitwidth) def find_offset_and_scale(self): '''Tries to find the offset of the vbi data in the raw samples.''' # Split into chunks and ensure there is something "interesting" in each target = gauss(self.vbi, self.gauss_sd_offset) d = [np.std(target[x:x+128]) < 5.0 for x in range(64, 1440, 128)] if any(d): return False low = 64 high = 256 target = gauss(self.vbi[low:high], self.gauss_sd_offset) def _inner(offset): self.g.set_offset(offset) self.g.update_cri(low, high) guess_scaled = self.g.convolved[low:high] mask_scaled = self.g.mask[low:high] a = guess_scaled*mask_scaled b = np.clip(target*mask_scaled, self.black, 256) scale = a.std()/b.std() b -= self.black b *= scale a = np.clip(a, 0, 256*scale) return np.sum(np.square(b-a)) offset = fminbound(_inner, self.offset_low, self.offset_high) # call it also to set self.offset and self.scale return (_inner(offset) < 10) def make_guess_mask(self): a = [] for i in range(42*8): (low, high) = self.g.get_bit_pos(i) a.append(self.vbi[low:high]) mins = np.array([min(x) for x in a]) maxs = np.array([max(x) for x in a]) avgs = np.array([np.array(x).mean() for x in a]) for i in range(42): mini = mins[i*8:(i+1)*8] maxi = maxs[i*8:(i+1)*8] avgi = avgs[i*8:(i+1)*8] self._mask0[i] = 0xff for j in range(8): if mini[j] < self.thresh_low: self._mask0[i] &= ~(1<<j) if maxi[j] > self.thresh_high: self._mask1[i] |= (1<<j) tmp = self._mask1 & self._mask0 self._mask0 |= self._mask1 self._mask1 = tmp def make_possible_bytes(self, possible_bytes): def masked(b, n): m0 = util.m0s[self._mask0[n]] m1 = util.m1s[self._mask1[n]] m = m0 & m1 & b if m: return m else: mm0 = m0 & b mm1 = m1 & b if len(mm0) < len(mm1): return mm0 or mm1 or b else: return mm1 or mm0 or b self.possible_bytes = [masked(b,n) for n,b in enumerate(possible_bytes)] def _deconvolve_make_diff(self, (low, high)): a = normalise(self.g.convolved) diff_sq = np.square(a - self.target) return np.sum(diff_sq) # an interesting trick I discovered. # bias the result towards the curent area of interest return np.sum(diff_sq[:low]) + 2.6*np.sum(diff_sq[low:high]) + np.sum(diff_sq[high:])
#!/usr/bin/env python from flask import Flask, render_template, redirect, url_for, session from flask_wtf import Form from wtforms.fields import RadioField, StringField, SubmitField from wtforms.validators import Required from guess import Guess, GuessError app = Flask(__name__) app.config["SECRET_KEY"] = "secret!" game = Guess("Python") game.expand("Python", "C++", "Is it interpreted?", False) game.expand("C++", "Java", "Does it run on a VM?", True) class YesNoQuestionForm(Form): answer = RadioField("Your answer", choices=[("yes", "Yes"), ("no", "No")]) submit = SubmitField("Submit") class LearnForm(Form): language = StringField("What language did you pick?", validators=[Required()]) question = StringField( "What is a question that differentiates your " "language from mine?", validators=[Required()] ) answer = RadioField("What is the answer for your language?", choices=[("yes", "Yes"), ("no", "No")]) submit = SubmitField("Submit") @app.route("/") def index():