pyhton實現猜單詞遊戲

2020-10-16 14:00:12

直接上程式碼,解釋在註釋,不懂評論留言,必回

'''1 猜單詞遊戲
計算機隨機產生一個單詞,打亂字母順序,供玩家猜測,採用控制字元介面。例如:
亂序後單詞: luebjm
請你猜:jumble
真棒 ,你猜對了!
是否繼續(Y/N):
…'''
import re
import random
#隨意擷取的段落
ch = ''' I like to be happy
      Life is a colorful picture full of different feelings I'd like to be happy because happiness is important to everyone.
      I have an unforgettable experience to share with you.
      Last Sunday my parents gave me some pocket money and with the money I bought some books instead of snacks.
      The next day I took the books to school. After lunch, I showed the books to my classmates and we read together.
      We learned a lot from the interesting books. Both reading and sharing made  me happy,
     How I wish I were happy every day in rnv life!'''
#正規表示式匹配去掉【】內的字元
#re.sub的用法
#split()返回的是一個list
#set轉為集合去重
word =re.sub("[\n.,!']" ,"",ch)
words = list(set(word.split()))


print("遊戲開始")

isgo = 'y'

while(isgo=='y' or isgo=='Y'):
    rword = random.choice(words)
    cword = rword
    jword = ""
    while rword:
        p = random.randrange(len(rword))
        jword+=rword[p]
        rword = rword[:p]+rword[(p+1):]
    print("亂序後的單詞:",jword)
    print()
    gword = input("請輸入單詞:")
    while gword!=cword and gword!="":
        print("猜錯了,請繼續")
        gword = input("請再次輸入單詞")
    if gword == cword:
        print("真棒,你猜對了\n")
    isgo = input("\n請問是否繼續(Y/N) : ")