python成语接龙
时间: 2023-11-28 22:45:34 浏览: 327
以下是一个简单的Python成语接龙的例子,它从一个文本文件中读取成语列表,然后使用循环遍历来完成成语接龙游戏。代码中的注释非常详细,适合新手学习使用。
```python
import random
# 从文件中读取成语列表
def get_chengyu_list():
with open('chengyu.txt', 'r', encoding='utf-8') as f:
chengyu_list = [line.strip() for line in f]
return chengyu_list
# 判断两个成语是否可以接龙
def can_connect(last_word, next_word):
return last_word[-1] == next_word[0]
# 从成语列表中随机选择一个成语作为起始成语
def get_first_word(chengyu_list):
return random.choice(chengyu_list)
# 从成语列表中选择一个与上一个成语可以接龙的成语
def get_next_word(chengyu_list, last_word):
for word in chengyu_list:
if can_connect(last_word, word):
return word
return None
# 主函数,控制游戏流程
def play_game():
chengyu_list = get_chengyu_list()
last_word = get_first_word(chengyu_list)
print('起始成语:', last_word)
while True:
next_word = get_next_word(chengyu_list, last_word)
if next_word is None:
print('没有可以接龙的成语了,游戏结束!')
break
print('上一个成语:', last_word)
print('下一个成语:', next_word)
last_word = next_word
input_word = input('请输入一个成语:')
if not can_connect(last_word, input_word):
print('你输了!')
break
last_word = input_word
play_game()
```
阅读全文
相关推荐














