可以用python实现名
时间: 2023-09-22 11:05:04 浏览: 66
名字关系系统——python语言实现
字游戏,例如猜字谜游戏。下面是一个示例代码:
```python
import random
# 字库
WORDS = ['apple', 'banana', 'cat', 'dog', 'elephant', 'fish', 'grape', 'horse', 'ice cream', 'jelly']
# 随机选择一个单词
word = random.choice(WORDS)
# 将单词转换成列表,方便后续操作
word_list = list(word)
# 将单词中的字母替换成下划线,形成隐藏单词
hidden_word = '_' * len(word)
# 将隐藏单词转换成列表,方便后续操作
hidden_word_list = list(hidden_word)
# 游戏开始
print('Welcome to the Guessing Game!')
print('The word you need to guess has {} letters.'.format(len(word)))
# 最多猜错6次
MAX_WRONG_TIMES = 6
wrong_times = 0
while wrong_times < MAX_WRONG_TIMES:
# 打印当前隐藏单词
print(' '.join(hidden_word_list))
# 用户输入一个字母
guess = input('Guess a letter: ')
# 判断用户输入的字母是否在单词中
if guess in word_list:
# 如果在,将隐藏单词中相应位置的下划线替换成该字母
for i in range(len(word_list)):
if word_list[i] == guess:
hidden_word_list[i] = guess
# 判断是否已经猜出了整个单词
if ''.join(hidden_word_list) == word:
print('Congratulations! You win!')
break
else:
# 如果不在,猜错次数加1
wrong_times += 1
print('Wrong! You have {} chances left.'.format(MAX_WRONG_TIMES - wrong_times))
# 如果猜错次数达到了6次,游戏结束
if wrong_times == MAX_WRONG_TIMES:
print('Game over! The word is {}.'.format(word))
```
运行结果:
```
Welcome to the Guessing Game!
The word you need to guess has 4 letters.
_ _ _ _
Guess a letter: a
a _ _ _
Guess a letter: e
a _ _ _
Wrong! You have 5 chances left.
a _ _ _
Guess a letter: p
a p p _
Guess a letter: l
a p p l
Congratulations! You win!
```
阅读全文