Python 猜词游戏--多步骤猜词+评分系统
老师下发了一个多步骤猜词游戏
游戏流程:给出了两个列表,分别存储8位单词和6-8位单词,分别代表不同的难度
用户首先需要选择难度,然后随机抽取一个单词作为securityword。
到这一步我都写出来了。但是我在用户进行猜测的代码上非常困惑。
具体需求如下:
用户需要进行8次猜测,第八次猜测输入完整单词。
每猜对一个元音及其位置正确给14分,每猜对一个辅音位置正确给12分,
猜对了字母但是位置错误的给5分。
eg: c r u s h i n g == security word
guess c r (后六位为空) --------------- 12*2 = 24
guess (前四个为空)+ c a l s ---------------- 0 (虽然 c 和 s 都在 crushing中,但是其位置对应的是hing,没有相同的字母,得分为0)
如果输入的字符长度超出security word,则提示长度错误,重新输入。
测试表:

实际代码运行界面:

求大佬教教这个该怎么写呀。
回答
代码:
import randomwords=['crushing'] #目标词
yy='aeiou'  #元音字母
def Cal(inpt,tar,loc): #计算得分
    point=0 #初始化总分0
    for i in range(loc[1]-loc[0]+1):    #循环猜测位数次
        k=i+loc[0]  #生成目标词的对应位置
        if inpt[i]==tar[k]: #如果猜测的某一位正确
            if inpt[i] in yy:   #如果是元音字母
                point+=14       #加14分
            else:               #如果是辅音字母
                point+=12       #加12分
        elif inpt[i] in tar[loc[0]:loc[1]+1]:   #如果位置错误但是有该字母
            point+=5        #加5分
    return point    #返回总分数
def GuessN(n,tar):  #第n次猜测
    loc=[(0,1),(1,3),(4,7),(3,5),(3,6),(5,7),(2,7),(0,7)]   #每一次的猜测位置list
    string='Guess '+str(n+1)+'|'    #生成Guess x 字符串
    for j in range(8):  #8次循环
        if j>=loc[n][0] and j<=loc[n][1]:   #如果该位置是猜测位
            string+=' * |'  #该位添加*
        else:               #否则
            string+=' - |'  #该位添加-
    print(string)   #打印Guess x| * | * |……
    print('-------------------------------------')
    while 1:    #死循环 用于猜测输入是否正确
        inpt=input('Now enter Guess '+str(n+1)+':') #获得输入
        if len(inpt)==loc[n][1]-loc[n][0]+1:    #如果输入位数正确
            break   #跳出循环
    points=Cal(inpt,tar,loc[n]) #调用计算得分
    print('%d Points' % points) #输出得分
    if points==100: #如果100分
        print('You win')    #则输出You win
def Guess():    #主函数
    tar=words[random.randint(0,len(words)-1)]   #随机挑选目标词(本例只有一个)
    print('Now try and guess the word, step by step!!')
    print('    | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |')
    print('-------------------------------------')
    for i in range(8):  #循环8次输入
        GuessN(i,tar)   #进行单次猜测
Guess() #调用主函数
效果:
以上是 Python 猜词游戏--多步骤猜词+评分系统 的全部内容, 来源链接: utcz.com/a/41123.html




