python實現(xiàn)簡單猜單詞游戲
本文實例為大家分享了python實現(xiàn)猜單詞游戲的具體代碼,供大家參考,具體內(nèi)容如下
電腦根據(jù)單詞列表隨機生成一個單詞,打印出這個單詞長度個 ‘ _ ’ ,玩家隨機輸入一個這個單詞可能包含的英文字母,如果玩家猜對了,電腦則會在正確的空格處填寫這個字母,如果沒有猜對,游戲次數(shù)就減一。如果玩家在游戲次數(shù)減為零前猜對這個單詞的所有字母,則玩家獲勝,否則玩家輸?shù)舯荣悺?/p>
from random import*words = ’tiger lion wolf elephant zebra ducksheep rabbit mouse’.split() #得到要猜的神秘單詞def getWord(wordList): n = randint(0,len(wordList)-1) return wordList[n] #游戲界面def display(word,wrongLetters,rightLetters,chance): print(’你還有{:n}次機會’.format(chance).center(40,’-’)) print(’已經(jīng)猜錯的字母:’+ wrongLetters) print() blanks = ’_’*len(word) for i in range(len(word)): if word[i] in rightLetters: blanks = blanks[:i] + word[i] +blanks[i+1:] for i in blanks: print(i+’ ’,end=’’) print() print() #從玩家的輸入得到一個猜測的字母def getLetter(alreadyGuessed): while True: print(’請輸入一個可能的字母:’) guess = input() guess = guess.lower() if guess[0] in alreadyGuessed: print(’你已經(jīng)猜過這個字母了!’) elif guess[0] not in ’qwertyuiopasdfghjklzxcvbnm’: print(’請輸入一個英文字母!(a-z)’) else: return guess[0] #是否再玩一次def playAgain(): print(’是否在玩一次?(y/n)’) s = input() s = s.lower() if s[0] == ’y’: return 1 return 0 #游戲初始化wrongLetters = ’’rightLetters = ’’word = getWord(words)chance = 6 #初始為6次機會done = False while True: display(word,wrongLetters,rightLetters,chance) guess = getLetter(wrongLetters+rightLetters) if guess in word: rightLetters = rightLetters+ guess foundAll = True for i in range(len(word)): if word[i] not in rightLetters: foundAll = False break if foundAll: print(’你真棒,這個單詞就是’+ word +’,你贏了!’) done = True else: wrongLetters = wrongLetters + guess chance = chance - 1 if chance == 0: display(word,wrongLetters,rightLetters,chance) print('你已經(jīng)沒有機會了!你一共猜錯了'+str(len((wrongLetters))+'次,猜對了'+str(len(rightLetters))+'次,正確的單詞是:'+ word) done = True if done: if playAgain(): wrongLetters = ’’ rightletters = ’’ word = getWord(words) chance = 6 #初始為6次機會 done = 0 else: break
再為大家提供一段代碼:python猜單詞游戲,作為補充,感謝原作者的分享。
import randomWORDS = ('math','english','china','history')right = ’Y’print('歡迎參加猜單詞游戲!') while right==’Y’ or right==’y’: word=random.choice(WORDS) correct=word newword = ’’ while word: pos=random.randrange(len(word)) newword+=word[pos] #將word單詞下標為pos的字母去掉,取pos前面和后面的字母組成新的word word = word[:pos]+word[(pos+1):] #保證隨機字母出現(xiàn)不會重復(fù) print('你要猜測的單詞為:',newword) guess = input('請輸入你的答案:') count=1 while count<5: if guess!=correct: guess = input('輸入的單詞錯誤,請重新輸入:') count+=1 else : print('輸入的單詞正確,正確單詞為:',correct) break if count == 5: print('您已猜錯5次,正確的單詞為:',correct) right = input('是否繼續(xù),Y/N:')
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 簡述JAVA同步、異步、阻塞和非阻塞之間的區(qū)別2. 利用php來自動調(diào)用不同服務(wù)器上的flash3. IntelliJ IDEA設(shè)置默認瀏覽器的方法4. Python TestSuite生成測試報告過程解析5. PHP基礎(chǔ)之流程控制3——while/do-while6. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法7. python操作數(shù)據(jù)庫獲取結(jié)果之fetchone和fetchall的區(qū)別說明8. IntelliJ IDEA設(shè)置背景圖片的方法步驟9. springboot的yml配置文件通過db2的方式整合mysql的教程10. 解決AJAX返回狀態(tài)200沒有調(diào)用success的問題
