本文實例為大家分享了Python實現(xiàn)簡單猜單詞的具體代碼,供大家參考,具體內(nèi)容如下
游戲說明:
由程序隨機(jī)產(chǎn)生一個單詞,打亂該單詞字母的排列順序,玩家猜測原來的單詞。
游戲關(guān)鍵點:
1.如何產(chǎn)生一個單詞?
2.如何打亂單詞字母的排列順序?
設(shè)計思路:
采用了元組(tuple)和random模塊。
元組作為單詞庫,使用random模塊隨機(jī)取一個單詞。
random模塊隨機(jī)選取字母,對字符串進(jìn)行切片組合獲得亂序單詞。
關(guān)鍵點圖示:
獲得亂序單詞,注意觀察word、jumble、position的變化。
測試運行效果圖示:
源代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
import random #創(chuàng)建單詞序列元組(單詞庫) WORDS = ( "python" , "juice" , "easy" , "difficult" ,\ "answer" , "continue" , "phone" , "hello" , "pose" , "game" ) #顯示游戲歡迎界面 print ( """ 歡迎參加猜單詞游戲 把原本亂序的字母組合成一個正確的單詞 """ ) #無論猜的對錯,實現(xiàn)游戲循環(huán)! iscontinue = "y" #輸入Y循環(huán) while iscontinue = = "y" or iscontinue = = "Y" : #從序列中隨機(jī)挑選出一個單詞 word = random.choice(WORDS) #print(type(word)) #保存正確的單詞 correct = word #創(chuàng)建亂序后的單詞 jumble = "" while word: #word不是空串循環(huán) #根據(jù)word的長度,產(chǎn)生亂序字母的隨機(jī)位置 position = random.randrange( len (word)) #將position位置的字母組合到亂序后的單詞后面 jumble + = word[position] #通過切片,將position位置的字母從原單詞中刪除 word = word[:position] + word[position + 1 :] #print(jumble) print ( "亂序后的單詞:" + jumble) #玩家猜測單詞 guess = input ( "\n請猜測:" ) while guess ! = correct and guess ! = "": print ( "\n猜測錯誤,請重猜或(回車)結(jié)束猜測該單詞!" ) guess = input ( "\n請輸入:" ) if guess = = correct: print ( "\n真棒,你猜對了!" ) iscontinue = input ( "\n是否繼續(xù)(Y/N):" ) |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/weixin_41995541/article/details/117884983