本文实例为大家分享了python实现猜单词游戏的具体代码,供大家参考,具体内容如下
电脑根据单词列表随机生成一个单词,打印出这个单词长度个 ‘ _ ' ,玩家随机输入一个这个单词可能包含的英文字母,如果玩家猜对了,电脑则会在正确的空格处填写这个字母,如果没有猜对,游戏次数就减一。如果玩家在游戏次数减为零前猜对这个单词的所有字母,则玩家获胜,否则玩家输掉比赛。
from random import*
words = 'tiger lion wolf elephant zebra ducksheep rabbit mouse'.split()
#得到要猜的神秘单词
def getWord(wordList):
n = randint(0,len(wordList)-1)
return wordList[n]
#游戏界面
def display(word,wrongLetters,rightLetters,chance):
print('你还有{:n}次机会'.format(chance).center(40,'-'))
print('已经猜错的字母:'+ wrongLetters)
print()
blanks = '_'*len(word)
for i in range(len(word)):
if word[i] in rightLetters:
blanks = blanks[:i] + word[i] +blanks[i+1:]
for i in blanks:
print(i+' ',end='')
print()
print()
#从玩家的输入得到一个猜测的字母
def getLetter(alreadyGuessed):
while True:
print('请输入一个可能的字母:')
guess = input()
guess = guess.lower()
if guess[0] in alreadyGuessed:
print('你已经猜过这个字母了!')
elif guess[0] not in 'qwertyuiopasdfghjklzxcvbnm':
print('请输入一个英文字母!(a-z)')
else:
return guess[0]
#是否再玩一次
def playAgain():
print('是否在玩一次?(y/n)')
s = input()
s = s.lower()
if s[0] == 'y':
return 1
return 0
#游戏初始化
wrongLetters = ''
rightLetters = ''
word = getWord(words)
chance = 6 #初始为6次机会
done = False
while True:
display(word,wrongLetters,rightLetters,chance)
guess = getLetter(wrongLetters+rightLetters)
if guess in word:
rightLetters = rightLetters+ guess
foundAll = True
for i in range(len(word)):
if word[i] not in rightLetters:
foundAll = False
break
if foundAll:
print('你真棒,这个单词就是'+ word +',你赢了!')
done = True
else:
wrongLetters = wrongLetters + guess
chance = chance - 1
if chance == 0:
display(word,wrongLetters,rightLetters,chance)
print("你已经没有机会了!你一共猜错了"+str(len((wrongLetters))+"次,猜对了"+str(len(rightLetters))+"次,正确的单词是:"+ word)
done = True
if done:
if playAgain():
wrongLetters = ''
rightletters = ''
word = getWord(words)
chance = 6 #初始为6次机会
done = 0
else:
break
再为大家提供一段代码:python猜单词游戏,作为补充,感谢原作者的分享。
import random
WORDS = ("math","english","china","history")
right = 'Y'
print("欢迎参加猜单词游戏!")
while right=='Y' or right=='y':
word=random.choice(WORDS)
correct=word
newword = ''
while word:
pos=random.randrange(len(word))
newword+=word[pos]
#将word单词下标为pos的字母去掉,取pos前面和后面的字母组成新的word
word = word[:pos]+word[(pos+1):] #保证随机字母出现不会重复
print("你要猜测的单词为:",newword)
guess = input("请输入你的答案:")
count=1
while count<5:
if guess!=correct:
guess = input("输入的单词错误,请重新输入:")
count+=1
else :
print("输入的单词正确,正确单词为:",correct)
break
if count == 5:
print("您已猜错5次,正确的单词为:",correct)
right = input("是否继续,Y/N:")
以上就是本文的全部内容,希望对大家的学习有所帮助
欢迎大家点赞,留言,转发,转载,感谢大家的相伴与支持
万水千山总是情,点个【在看】行不行
*声明:本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权事