本文實例為大家分享了Python實現簡單猜單詞的具體代碼,供大家參考,具體內容如下
游戲說明:
由程序隨機產生一個單詞,打亂該單詞字母的排列順序,玩家猜測原來的單詞。
游戲關鍵點:
1.如何產生一個單詞?
2.如何打亂單詞字母的排列順序?
設計思路:
采用了元組(tuple)和random模塊。
元組作為單詞庫,使用random模塊隨機取一個單詞。
random模塊隨機選取字母,對字符串進行切片組合獲得亂序單詞。
關鍵點圖示:
獲得亂序單詞,注意觀察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 #創建單詞序列元組(單詞庫) WORDS = ( "python" , "juice" , "easy" , "difficult" ,\ "answer" , "continue" , "phone" , "hello" , "pose" , "game" ) #顯示游戲歡迎界面 print ( """ 歡迎參加猜單詞游戲 把原本亂序的字母組合成一個正確的單詞 """ ) #無論猜的對錯,實現游戲循環! iscontinue = "y" #輸入Y循環 while iscontinue = = "y" or iscontinue = = "Y" : #從序列中隨機挑選出一個單詞 word = random.choice(WORDS) #print(type(word)) #保存正確的單詞 correct = word #創建亂序后的單詞 jumble = "" while word: #word不是空串循環 #根據word的長度,產生亂序字母的隨機位置 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猜測錯誤,請重猜或(回車)結束猜測該單詞!" ) guess = input ( "\n請輸入:" ) if guess = = correct: print ( "\n真棒,你猜對了!" ) iscontinue = input ( "\n是否繼續(Y/N):" ) |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_41995541/article/details/117884983