您好,登錄后才能下訂單哦!
這篇文章主要講解了python實現猜單詞小游戲的方法,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
游戲邏輯:就像我們曾經英語學習機上的小游戲一樣,電腦會從事先預置的詞庫中抽取單詞,然后給出單詞的字母數量,給定猜解次數,然后讓玩家進行猜測,并給出每次猜測的正確字母與錯誤字母。
涉及知識點:random.randint(),print(),input()(raw_input())
參考實現代碼:
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function import os import sys import random import time #單詞庫 Words = ['apple','pear','banana'] #單詞隨機選擇函數 def getRandomWord(): global Words return Words[random.randint(0,len(Words)-1)] #猜測流程 def getGuess(): while True: guess = raw_input("Guess the Word: ") for letter in guess: if letter in wrongLetters: print("The char: " + letter + " you have already guessed") continue break return guess #判別顯示流程 def displayGame(secretLetters,wrongLetters,secretWord): global guess global count print("Info: ") for letter in guess: if letter in secretWord: secretLetters += letter else: wrongLetters += letter print("SecretLetters: ",end = '') for letter in secretLetters: print(letter,end = ' ') print() print("WrongLetters: ",end = '') for letter in wrongLetters: print(letter,end = ' ') print() print("Count: "+str(count)) blanks = '_'*len(secretWord) for i in range(len(guess)): if i >=len(secretWord): break if secretWord[i]==guess[i]: blanks = blanks[:i] + secretWord[i] + blanks[i+1:] print("Word: ",end = '') for i in blanks: print(i,end=" ") print() print() #主流程 secretLetters = '' wrongLetters = '' secretWord = '' guess = "" count = 6 os.system('cls') secretWord = getRandomWord() while True: displayGame(secretLetters,wrongLetters,secretWord) guess = getGuess() if guess == secretWord: print ("You win !") break else: if count <= 0: print("You lose !") break else: count -= 1 continue
看完上述內容,是不是對python實現猜單詞小游戲的方法有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。