Q:基于网络学堂提供的Hangman词表,实现计算机随机选择词表中单词,用户尝试猜测单词中的字母的互动过程。
import random
import numpy
print("游戏开始!!\n")
fr=open('hangman词表.txt','r')
content=fr.readlines()
wd=random.sample(content, 1)[0]
nwrong=0
l=len(wd)-1
flag=numpy.zeros(l)
print("该单词长度为",l)
for i in range(l):
print("_",end='')
print()
while True:
f=0
scape=0
if nwrong>=7:
print("You lose!\n")
print("正确答案为",wd)
break
print("\n您还有",7-nwrong,"次出错的机会")
guess=input("请输入您本次猜测的字母:")
for i in range(l):
if wd[i]==guess:
print(wd[i],end='')
flag[i]=1
f=1
elif flag[i]==1:
print(wd[i],end='')
else:
print("_",end='')
scape=1
if f==0:
print("\n很可惜没猜中,下次加油哦!")
nwrong+=1
if f==1:
print("\n恭喜你猜对啦!继续加油")
if scape==0:
print("\nYou Win!")
Break